缓存方案(JetCache)
作者: luote (luote) · 个人主页 luote996.cn
脚手架集成 JetCache(阿里开源),通过注解即可使用企业级缓存能力。
已解决的问题
| 问题 | 方案 |
|---|---|
| 缓存穿透 | cacheNullValue = true + @CachePenetrationProtect |
| 缓存击穿 | @CachePenetrationProtect 单线程回源 |
| 缓存雪崩 | 本地/远程分层过期 + 过期抖动工具方法 |
| 热点 key | CacheType.BOTH(Caffeine 本地 + Redis 远程) |
| 大 key | CacheValueGuard 写入前体积校验 |
| 缓存预热 | LuoteCacheWarmup 启动加载 admin 用户 |
怎么用
参考 UserCacheService:
java
@Cached(
name = CacheConstant.USER,
key = "#id",
cacheType = CacheType.BOTH,
syncLocal = true,
cacheNullValue = true,
expire = 3600,
localExpire = 300
)
@CachePenetrationProtect
public User getById(Long id) {
return userMapper.selectById(id);
}
@CacheInvalidate(name = CacheConstant.USER, key = "#id")
public void evict(Long id) {
}新增业务模块时:复制 UserCacheService 模式,改 name 和 key 即可。
配置
application.yml:
yaml
luote:
cache:
warmup-enabled: true
max-value-bytes: 51200
jetcache:
local:
default:
type: caffeine
limit: 128
remote:
default:
type: redis.lettuce
keyPrefix: "luote:cache:"注意事项
@Cached方法须写在独立 Service 中(避免同类自调用导致 AOP 失效)- 更新/删除数据后务必
@CacheInvalidate - 列表分页不建议直接缓存,可缓存热点详情
- 超大对象不要进缓存,走
CacheValueGuard或拆分字段