本模块简单的实现了 Google Guava Cache
和 Redis
的 Spring
缓存版,还没有使用过 Spring Cache
的小伙伴,可以自行谷歌了解下
@Bean
public GuavaCacheManager guavaCacheManager() {
// @formatter:off
CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
.expireAfterWrite(30, TimeUnit.MINUTES)
.softValues()
.initialCapacity(128)
.maximumSize(1024);
// @formatter:on
return CacheUtils.newGuavaCacheManager(cacheBuilder, "cache1", "cache2");
}
@Bean
public GuavaCacheManager guavaCacheManager() {
Map<String, GuavaCacheCreator> creatorMap = new HashMap<>(2, 1);
// 不同的缓存使用不同的缓存策略
creatorMap.put("cache1", CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES));
creatorMap.put("cache2", CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES));
return CacheUtils.newGuavaCacheManager(creatorMap);
}
提供多种创建方式,你可以选择任意你喜欢的方式创建
@EnableCaching
@Cacheable(value = "cache1", key = "#root.method", cacheManager = "guavaCacheManager")
或者
@Cacheable(value = "cache2", key = "#root.args", cacheManager = "guavaCacheManager")
当然,你也可以不使用注解,直接在代码中手动缓存,使用你用到的 CacheManager
即可