spring boot caffeine

spring 5中取消了Guava cache做为本地缓存,推荐使用 caffeine. 具体缘由参见官网测试参数。java

<dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-cache</artifactId>
            </dependency>
            <dependency>
                <groupId>com.github.ben-manes.caffeine</groupId>
                <artifactId>caffeine</artifactId>
            </dependency>
spring.cache.caffeine.spec=maximumSize=200,expireAfterAccess=600s

能够在配置文件中application.properties 配置容量,过时时间,cache namegit

建议是在代码中,配置,因代码中配置更加灵活,能够设置每个cache name的 过时时间,容量github

@EnableCaching
@Configuration
public class CacheConfig {
    public static final int DEFAULT_MAXSIZE = 50000;
    public static final int DEFAULT_TTL = 24;

    /**
     * 建立缓存,有效期,容量
     */
    public enum Caches {
        // 默认 24小时 5W
        getDefault,
        // 1小时,最大容量1000
        getOtherthing(1, 1000),
        ;
        Caches() {
        };

        Caches(
               int ttl) {
            this.ttl = ttl;
        }

        Caches(int ttl, int maxSize) {
            this.ttl = ttl;
            this.maxSize = maxSize;
        }

        // 最大數量
        private int maxSize = DEFAULT_MAXSIZE;
        // 过时时间(小时)
        private int ttl = DEFAULT_TTL;

        public int getMaxSize() {
            return maxSize;
        }

        public int getTtl() {
            return ttl;
        }
    }

    /**
     * 建立基于Caffeine的Cache Manager
     * @return
     */
    @Bean
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ArrayList<CaffeineCache> caches = new ArrayList<CaffeineCache>();
        for (Caches c : Caches.values()) {
            caches.add(new CaffeineCache(c.name(),
                                         Caffeine.newBuilder().recordStats()
                                             .expireAfterWrite(c.getTtl(), TimeUnit.HOURS)
                                             .maximumSize(c.getMaxSize())
                                             .build()));
        }
        cacheManager.setCaches(caches);
        return cacheManager;
    }
}

代码:https://gitee.com/emperors/spring-boot-integration.git spring

相关文章
相关标签/搜索