spring boot caffeine


声明:本文转载自https://my.oschina.net/u/3247419/blog/1555599,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

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

   <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 name

建议是在代码中,配置,因代码中配置更加灵活,可以设置每一个cache name的 过期时间,容量

@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 

本文发表于2017年10月24日 18:34
(c)注:本文转载自https://my.oschina.net/u/3247419/blog/1555599,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 2376 讨论 0 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1