Spring Boot 使用Caffeine缓存

  Spring Boot 使用Caffeine缓存

  Caffeine官方的介绍

  demo

  Caffeine配置参数

  Caffeine是Java8重写Guava缓存,取代Guava缓存。

  Spring Cache相关注解基础请查看这篇文章

  Caffeine官方的介绍

  caffeine官网

  Caffeine是基于Java8的高性能,接近完美的缓存库。

  demo

  pom.xml

  引入spring-context-support

  com.github.ben-manes.caffeine

  caffeine

  2.8.0

  org.springframework

  spring-context-support

  或者spring-boot-starter-cache

  com.github.ben-manes.caffeine

  caffeine

  2.8.0

  org.springframework.boot

  spring-boot-starter-cache

  Caffeine配置参数

  属性  说明

  initalCapacity  初始空间大小

  maximumSize  缓存最大条数

  maximumWeight  缓存的最大权重

  expireAfterAccess  最后一次写入或访问后经过固定时间过期

  expireAfterWrite  最后一次写入后经过固定时间过期

  refreshAfterWrite  创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存

  weakKeys  打开key的弱引用

  weakValues  打开value的弱引用

  softValues  打开value的软引用

  recordStats  开发统计功能

  注意

  refreshAfterWrite 要实例 LoadingCache 否则报错

  java.lang.IllegalStateException: refreshAfterWrite requires a LoadingCache

  application.yml

  spring:

  cache:

  cache-names:

  - cache1

  - cache2

  type: caffeine

  caffeine:

  spec:郑州人流手术费用 http://www.zzzzyy120.com/

  maximumSize=500,expireAfterAccess=600s

  yml文件中的配置也可以通过bean来配置

  CacheConfig.java

  package com.jsong.wiki.blog.config;

  import com.github.benmanes.caffeine.cache.CacheLoader;

  import com.github.benmanes.caffeine.cache.Caffeine;

  import org.checkerframework.checker.nullness.qual.NonNull;

  import org.checkerframework.checker.nullness.qual.Nullable;

  import org.springframework.cache.CacheManager;

  import org.springframework.cache.caffeine.CaffeineCacheManager;

  import org.springframework.context.annotation.Bean;

  import org.springframework.context.annotation.Configuration;

  import java.util.concurrent.TimeUnit;

  @Configuration

  public class CacheConfig {

  @Bean("caffeineCacheManager")

  public CacheManager caffeineCacheManager() {

  CaffeineCacheManager cacheManager = new CaffeineCacheManager();

  cacheManager.setCaffeine(Caffeine.newBuilder()

  .maximumSize(10_1000)

  .expireAfterAccess(5, TimeUnit.SECONDS));

  return cacheManager;

  }

  /* 如果配置refreshAfterWrite要有这个bean,否则报错

  java.lang.IllegalStateException: refreshAfterWrite requires a LoadingCache*/

  @Bean

  public CacheLoader cacheLoader() {

  CacheLoader cacheLoader = new CacheLoader() {

  @Nullable

  @Override

  public Object load(@NonNull Object key) throws Exception {

  return null;

  }

  };

  return cacheLoader;

  }

  }

  CacheService.java

  package com.jsong.wiki.blog.service;

  import org.springframework.cache.annotation.*;

  import org.springframework.stereotype.Component;

  @EnableCaching

  @CacheConfig(cacheNames = "caffeineCacheManager")

  @Component

  public class CacheService {

  @Cacheable(value = "cache1", key = "#root.target")

  public String getName() {

  System.out.println("cache1");

  return "cache1";

  }

  }

猜你喜欢

转载自www.cnblogs.com/djw12333/p/12101717.html