- Springboot Cache使用
- 添加依赖
- 配置文件
- 注解使用
- 几个重要概念&缓存注解
- @Cacheable/@CachePut/@CacheEvict 主要的参数
- 注解使用案例
- 参考文章
org.springframework.boot
spring-boot-starter-cache
com.github.ben-manes.caffeine
caffeine
2.9.0
配置文件
普通默认配置:
@Configuration
@EnableCaching
public class SpringCacheConfig {
}
自定义过期时间配置:
@Configuration
@EnableCaching
public class SpringCacheConfig {
// 过期时间
private static int EXPIRE_SECONDS = 24 * 60 * 60;
@Bean
public CacheManager cacheManager(Ticker ticker) {
CaffeineCache riskWarningSpotList = buildCache("riskWarning:spotList", ticker, EXPIRE_SECONDS);
CaffeineCache riskMapSpotList = buildCache("riskMap:spotList", ticker, EXPIRE_SECONDS);
SimpleCacheManager manager = new SimpleCacheManager();
manager.setCaches(Lists.newArrayList(riskWarningSpotList, riskMapSpotList));
return manager;
}
private CaffeineCache buildCache(String name, Ticker ticker, int seconds) {
return new CaffeineCache(name, Caffeine.newBuilder()
.expireAfterWrite(seconds, TimeUnit.SECONDS)
.maximumSize(1000)
.ticker(ticker)
.build());
}
@Bean
public Ticker ticker() {
return Ticker.systemTicker();
}
}
注解使用
几个重要概念&缓存注解
| 名称 | 解释 |
|---|---|
| Cache | 缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、ConcurrentMapCache等 |
| CacheManager | 缓存管理器,管理各种缓存(cache)组件 |
| @Cacheable | 主要针对方法配置,能够根据方法的请求参数对其进行缓存 |
| @CacheEvict | 清空缓存 |
| @CachePut | 保证方法被调用,又希望结果被缓存。与@Cacheable区别在于是否每次都调用方法,常用于更新 |
| @EnableCaching | 开启基于注解的缓存 |
| keyGenerator | 缓存数据时key生成策略 |
| serialize | 缓存数据时value序列化策略 |
| @CacheConfig | 统一配置本类的缓存注解的属性 |
| 名称 | 解释 |
|---|---|
| value | 缓存的名称,在 spring配置文件中定义,必须指定至少一个。例如:@Cacheable(value=”mycache”) 或者@Cacheable(value={”cache1”,”cache2”} |
| key | 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合。例如:@Cacheable(value=”testcache”,key=”#id”) |
| condition | 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存/清除缓存例如:@Cacheable(value=”testcache”,condition=”#userName.length()>2”) |
| unless | 否定缓存。当条件结果为TRUE时,就不会缓存。@Cacheable(value=”testcache”,unless=”#userName.length()>2”) |
| allEntries(@CacheEvict ) | 是否清空所有缓存内容,缺省为 false,如果指定为true,则方法调用后将立即清空所有缓存。例如:@CachEvict(value=”testcache”,allEntries=true)beforeInvocation(@CacheEvict)是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存 |
例如:
@CachEvict(value=”testcache”,beforeInvocation=true)
@Cacheable(value = "riskMap:spotList",
key = "targetClass + methodName + #type + #observeTime + #dataTime")
@Override
public List spotList(String spotName, String province, String city, String cnties, String type, LocalDateTime observeTime, LocalDateTime dataTime) {
...
}
@Cacheable(value = "riskMap:spotInfo",
key = "targetClass + methodName + #type + #observeTime + #dataTime + #spotInfoId")
@Override
public RiskMapSpotInfoDetailVO spotInfo(Integer spotInfoId, String type, LocalDateTime observeTime, LocalDateTime dataTime) {
...
}
参考文章
springboot使用cache缓存
Spring Boot缓存配置不同到期时间
Spring SpEL表达式语言



