Spring Cache + Caffeine

Wu Jun 2019-12-25 15:59:03
Categories: > Tags:

Caffeine 是使用 Java8 对 Guava 缓存的重写版本,在 Spring Boot 2.0 中取代 Guava。

1 引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.6.2</version>
</dependency>

2 开启缓存

@EnableCaching

3 配置参数

注意:

spring:
  cache:
    type: CAFFEINE
    cache-names:
      - CacheName
    caffeine:
      spec: initialCapacity=50,maximumSize=1000,expireAfterWrite=10s,refreshAfterWrite=14400s

如果使用了 refreshAfterWrite 配置还必须指定一个 CacheLoader

@Configuration
public class CacheConfig {
    @Bean
    public CacheLoader<Object, Object> cacheLoader() {

        CacheLoader<Object, Object> cacheLoader = new CacheLoader<Object, Object>() {
            @Override
            public Object load(Object key) throws Exception {
                return null;
            }

            // 重写这个方法将oldValue值返回回去,进而刷新缓存
            @Override
            public Object reload(Object key, Object oldValue) throws Exception {
                return oldValue;
            }
        };
        return cacheLoader;
    }
}

使用

@Cacheable(value = "CacheName")