Spring Cache
简介
continew-starter-cache-springcache 是 ContiNew Starter 缓存模块基于 Spring Cache 的 Redis 缓存实现(@since 1.2.0),在 Redisson 之上提供 @Cacheable 等声明式缓存的自动配置,开箱即用。
主要特性
- 开箱即用: 引入依赖即可使用 Spring Cache 标准注解,无需手动配置 RedisCacheManager
- 乱码治理: 默认解决 Spring Cache(@Cacheable)Jackson 解析缓存乱码问题
- 默认 Key 策略: 内置缓存 Key 生成器,@Cacheable 未指定 key 时自动生效
- 配置直通: 兼容 Spring Boot 原生
spring.cache.*与 Redisson 配置风格
快速开始
引入依赖
xml
<dependency>
<groupId>top.continew.starter</groupId>
<artifactId>continew-starter-cache-springcache</artifactId>
</dependency>添加配置
本模块无专属配置属性类,缓存过期策略复用 Spring Boot 原生 spring.cache.* 配置(默认值由模块内置的 default-cache-springcache.yml 提供);Redis 连接与 Redisson 相关配置请查看:top.continew.starter.cache.redisson.autoconfigure.RedissonProperties。
yaml
--- ### Spring Cache 配置
spring.cache:
redis:
# 缓存过期时长(单位:毫秒,默认 -1,表示永不过期)
time-to-live: 7200000
# 是否允许缓存空值(默认 true,表示允许,可以解决缓存穿透问题)
cache-null-values: true使用 Spring Cache 注解
引入依赖后,直接使用 Spring Cache 标准注解即可,缓存值以 Jackson JSON 序列化存入 Redis。
java
@Service
public class DemoService {
@Cacheable(cacheNames = "demo", key = "'id:' + #id")
public DemoVo get(Long id) {
// 首次执行后结果缓存至 Redis,过期策略取 spring.cache.redis 配置
return ...;
}
@CacheEvict(cacheNames = "demo", key = "'id:' + #id")
public void update(DemoReq req) {
// ...
}
}不指定 key 时,使用内置 KeyGenerator 生成缓存 Key:方法名(下划线分隔后大写)+ : + 方法参数 JSON 的 SHA-256 摘要。
依赖链上的工具类
本模块依赖 continew-starter-cache-redisson,可一并使用其 RedisUtils(@since 1.0.0)、RedisLockUtils(@since 2.13.4)工具类,详情参见 Redisson 文档。
核心依赖
| 依赖 | 描述 |
|---|---|
| top.continew.starter:continew-starter-cache-redisson | Redisson 缓存支撑模块(Redis 客户端及分布式工具) |
| cn.hutool:hutool-crypto | Hutool 加密解密模块(用于缓存 Key 生成的 SHA-256 摘要) |