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