点击链接跳转「搜狐技术产品」原文🔗
你有没有过这样的经历:项目里到处都是 redisTemplate.opsForValue().set(),key 的命名全靠自觉,过期时间写死在代码里,本地缓存和远程缓存各管各的,数据不一致了只能手动清……
这不是个例。大部分 Java 项目用 Redis 做缓存,本质上就是在裸奔——功能是有了,但维护成本随着业务膨胀直线上升。
今天聊聊阿里巴巴开源的 JetCache,看看它怎么把缓存这件事做得更体面。
01
JetCache 是什么
JetCache 是阿里开源的 Java 缓存抽象框架,GitHub 上 5k+ Star(项目地址:https://github.com/alibaba/jetcache)。它不是 Redis 的替代品,而是在 Redis 之上提供了一层更优雅的抽象。你可以把它理解为缓存的 Spring Data——就像 Spring Data JPA 屏蔽了不同数据库的差异,JetCache 屏蔽了本地缓存和远程缓存的差异,给你一套统一的 API。
核心能力包括:
• 声明式缓存:注解搞定,不用写一行缓存代码
• 编程式缓存:Map 风格 API,灵活可控
• 多级缓存:本地 + 远程组合,并提供本地缓存失效广播机制
• 自动刷新:按固定间隔后台刷新,减少过期瞬间的集中回源
• 穿透保护:限制同一 key 的并发回源,减轻热点 key 失效时的压力
• 分布式锁:基于缓存实现分布式锁
02
先看对比:裸用 Redis vs JetCache
拿一个最常见的场景举例——根据用户 ID 查用户信息。
裸用 Redis 的写法:
@Service
public class UserService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public User getUserById(Long userId) {
String key = "user:" + userId;
User user = (User) redisTemplate.opsForValue().get(key);
if (user != null) {
return user;
}
user = userMapper.selectById(userId);
if (user != null) {
redisTemplate.opsForValue().set(key, user, 1, TimeUnit.HOURS);
}
return user;
}
public void updateUser(User user) {
userMapper.updateById(user);
redisTemplate.opsForValue().set("user:" + user.getUserId(), user, 1, TimeUnit.HOURS);
}
public void deleteUser(Long userId) {
userMapper.deleteById(userId);
redisTemplate.delete("user:" + userId);
}
}
问题明显:每个方法都要手动拼 key、手动处理序列化、手动设过期时间、手动维护缓存一致性。
JetCache 的写法:
public interface UserService {
@Cached(name = "user:", key = "#userId", expire = 3600,
cacheType = CacheType.BOTH, localExpire = 300)
User getUserById(Long userId);
@CacheUpdate(name = "user:", key = "#user.userId", value = "#user")
void updateUser(User user);
@CacheInvalidate(name = "user:", key = "#userId")
void deleteUser(Long userId);
}
三行注解,完事。而且 cacheType = CacheType.BOTH 意味着同时用了本地缓存和远程缓存,性能提升显著。
03
架构设计:Cache 抽象层
JetCache 的核心是 Cache<K, V> 接口,定义在 jetcache-core 模块中。它参考了 JSR 107(JCache 标准)的设计理念,同时做了很多实用扩展:
public interface Cache<K, V> extends Closeable {
// 基础操作
V get(K key);
void put(K key, V value);
boolean remove(K key);
// 带详细信息返回
CacheGetResult<V> GET(K key);
CacheResult PUT(K key, V value);
// 自动加载
V computeIfAbsent(K key, Function<K, V> loader);
// 批量操作
Map<K, V> getAll(Set<? extends K> keys);
void putAll(Map<? extends K, ? extends V> map);
// 原子操作
boolean putIfAbsent(K key, V value);
CacheResult PUT_IF_ABSENT(K key, V value, long expireAfterWrite, TimeUnit timeUnit);
// 分布式锁支持
AutoReleaseLock tryLock(K key, long expire, TimeUnit timeUnit);
boolean tryLockAndRun(K key, long expire, TimeUnit timeUnit, Runnable action);
}
这里有个巧妙的设计:大小写方法区分语义。
• 小写方法(get、put):简单直接;普通缓存访问失败不抛异常,get 返回 null、put 忽略结果、remove 返回 false。get 抛出 CacheInvokeException 的典型场景是 loader 回源时抛出异常
• 大写方法(GET、PUT):返回 CacheResult 对象,包含详细的操作结果
// 小写方法:简单场景
User user = cache.get(userId); // 未命中或缓存访问失败都返回 null
// 大写方法:需要知道失败原因
CacheGetResult<User> result = cache.GET(userId);
if (result.isSuccess()) {
return result.getValue();
} else if (result.getResultCode() == CacheResultCode.NOT_EXISTS) {
// 缓存不存在
} else if (result.getResultCode() == CacheResultCode.EXPIRED) {
// 缓存已过期
} else if (result.getResultCode() == CacheResultCode.FAIL) {
// Redis 连接失败等异常
}
CacheResultCode 枚举定义了六种状态值,在源码中可以清晰看到:
public enum CacheResultCode {
SUCCESS, // 操作成功
PART_SUCCESS, // 部分成功(多级缓存场景)
FAIL, // 操作失败
NOT_EXISTS, // 缓存不存在
EXISTS, // 已存在(putIfAbsent 场景)
EXPIRED // 已过期
}
这让你能精确区分"缓存没有"和"数据加载失败"两种情况,而不是统统返回 null——这在排查线上问题时非常关键。比如你可以针对 FAIL 状态降级处理,而不是直接返回 null 让业务层误以为"数据不存在"。
04
批量操作:减少网络往返
JetCache 提供了完整的批量操作 API,对于远程缓存特别有价值。批量接口通常可以减少网络往返(例如 Lettuce 的 GET_ALL 使用 MGET),但不同实现和不同操作的执行方式并不相同:
// 批量查询
Set<Long> userIds = Set.of(1L, 2L, 3L);
Map<Long, User> users = cache.getAll(userIds);
// 批量写入
Map<Long, User> userMap = new HashMap<>();
userMap.put(1L, user1);
userMap.put(2L, user2);
cache.putAll(userMap);
// 批量删除
cache.removeAll(userIds);
源码中 MultiGetResult 类封装了批量查询的结果:
public class MultiGetResult<K, V> extends CacheResult {
private Map<K, CacheGetResult<V>> values;
// 解包:只返回成功的值
public Map<K, V> unwrapValues() {
Map<K, V> map = new HashMap<>();
if (values != null) {
for (Map.Entry<K, CacheGetResult<V>> en : values.entrySet()) {
if (en.getValue().isSuccess()) {
map.put(en.getKey(), en.getValue().getValue());
}
}
}
return map;
}
}
批量查询的结果是"部分成功"模式:某些 key 命中,某些没命中,调用方需要根据返回的 Map 判断。unwrapValues 方法帮你过滤掉未命中的 key,只返回有效数据。
注意:批量操作不保证原子性。如果需要原子性,应该用 Redis 的事务或 Lua 脚本。
05
缓存层次:LocalCache 和 ExternalCache
JetCache 把缓存分成两大类,对应不同的存储位置和访问特性。
LocalCache(本地缓存):数据存在 JVM 堆内存中,访问速度最快(纳秒级),但容量有限,且不同节点之间数据不共享。源码中对应 AbstractEmbeddedCache 抽象类,支持两种实现:
• LinkedHashMapCache:基于 JDK 的 LinkedHashMap,支持 LRU 淘汰,适合简单场景
• CaffeineCache:基于高性能缓存库 Caffeine,采用 W-TinyLFU 淘汰算法,性能更优
ExternalCache(远程缓存):数据存在外部存储(如 Redis),容量大、可跨节点共享,但访问有网络开销(毫秒级)。源码中对应 AbstractExternalCache 抽象类,支持多种 Redis 客户端:
• RedisCache:基于 Jedis 客户端
• RedisLettuceCache:基于 Lettuce 客户端,支持原生异步操作
• RedissonCache:基于 Redisson 客户端
• RedisSpringDataCache:基于 Spring Data Redis
MultiLevelCache(多级缓存):组合本地和远程,读取时按顺序查找,写入时同时写入两级。这是 JetCache 多级缓存的核心实现,核心结构如下(简化示意):
public class MultiLevelCache<K, V> extends AbstractCache<K, V> {
private Cache[] caches; // 缓存层级数组,索引 0 是本地缓存
@Override
protected CacheGetResult<V> do_GET(K key) {
for (int i = 0; i < caches.length; i++) {
Cache cache = caches[i];
CacheGetResult result = cache.GET(key);
if (result.isSuccess()) {
// 命中后,回填上层缓存
CacheValueHolder<V> holder = result.getHolder();
checkResultAndFillUpperCache(key, i, holder);
return result;
}
}
return CacheGetResult.NOT_EXISTS_WITHOUT_MSG;
}
}
以上代码揭示了多级缓存的核心逻辑:逐级查找,命中后回填上层,保证下次访问能直接从更快的缓存获取。
06
CacheValueHolder:值包装机制
JetCache 内部用一个 CacheValueHolder 类包装所有缓存值。这个设计很关键,源码定义如下:
public final class CacheValueHolder<V> implements Serializable {
private V value;
private long expireTime; // 绝对过期时间戳
private long accessTime; // 最后访问时间(用于 access 过期)
public V getValue() { return value; }
public long getExpireTime() { return expireTime; }
}
每个缓存值都记录了精确的过期时间点。这带来两个好处:
1. 支持不同条目不同过期时间:同一个 cache 实例,不同 key 可以有不同的 TTL
2. 多级缓存可按配置保留远程剩余 TTL:远程缓存命中后回填本地时,可以选择沿用远程剩余过期时间
多级缓存回填时,源码会计算剩余 TTL:
private void checkResultAndFillUpperCache(K key, int i, CacheValueHolder<V> h) {
long currentExpire = h.getExpireTime();
long now = System.currentTimeMillis();
if (now <= currentExpire) {
long restTtl = currentExpire - now;
if (restTtl > 0) {
// 用剩余 TTL 写入上层缓存
PUT_caches(i, key, h.getValue(), restTtl, TimeUnit.MILLISECONDS);
}
}
}
上面这段代码对应“沿用远程剩余 TTL”的模式:如果远程缓存还剩 5 分钟过期,回填到本地缓存时也只存活 5 分钟。注意,如果配置了 localExpire,JetCache 会启用各层独立 TTL 的模式,本地缓存会按自己的 localExpire 过期,不能保证一定不比远程缓存“活得更久”。
07
本地缓存实现深度解析
JetCache 的本地缓存实现非常精巧。以 CaffeineCache 为例,源码展示了它是如何利用 Caffeine 的 Expiry 接口实现精确的过期控制:
public class CaffeineCache<K, V> extends AbstractEmbeddedCache<K, V> {
@Override
protected InnerMap createAreaCache() {
Caffeine<Object, Object> builder = Caffeine.newBuilder();
builder.maximumSize(config.getLimit()); // 最大容量
builder.expireAfter(new Expiry<Object, CacheValueHolder>() {
private long getRestTimeInNanos(CacheValueHolder value) {
long now = System.currentTimeMillis();
long ttl = value.getExpireTime() - now;
if (isExpireAfterAccess) {
ttl = Math.min(ttl, expireAfterAccess); // 访问过期和写入过期取较小值
}
return TimeUnit.MILLISECONDS.toNanos(ttl);
}
// ... 实现 expireAfterCreate、expireAfterUpdate、expireAfterRead
});
return new InnerMap() { ... };
}
}
每个缓存值都被包装成 CacheValueHolder,记录了精确的过期时间戳。Caffeine 的 Expiry 接口允许为每个条目设置不同的过期时间,这比传统的"统一过期"更灵活。
08
两种过期策略:expireAfterWrite vs expireAfterAccess
JetCache 支持两种过期策略,源码中 CacheConfig 定义了相关配置:
public class CacheConfig<K, V> implements Cloneable {
private long expireAfterWriteInMillis; // 写入后过期时间
private long expireAfterAccessInMillis; // 访问后过期时间
public boolean isExpireAfterAccess() {
return expireAfterAccessInMillis > 0;
}
}
两种策略的区别:
• expireAfterWrite:从数据写入缓存时开始计时,到期后过期,不管中间有没有被访问。适合配置类、静态数据等"写入后固定时间失效"的场景。
• expireAfterAccess:每次访问都会重置过期时间,适合会话、用户状态等"活跃数据保持,冷数据淘汰"的场景。用户频繁操作时,会话一直有效;长时间不操作,会话自动过期。
两者可以同时配置,取较短的那个。源码中的计算逻辑:
private long getRestTimeInNanos(CacheValueHolder value) {
long now = System.currentTimeMillis();
long ttl = value.getExpireTime() - now;
if (isExpireAfterAccess) {
ttl = Math.min(ttl, expireAfterAccess);
}
return TimeUnit.MILLISECONDS.toNanos(ttl);
}
使用场景举例:
// 写入后 1 小时过期(绝对过期):注解直接声明
@Cached(name = "config:", expire = 3600, timeUnit = TimeUnit.SECONDS)
// 访问后 30 分钟过期(滑动过期):注解不支持此属性,需通过 Builder API 配置
EmbeddedCacheBuilder<Long, Session> builder = LinkedHashMapCacheBuilder
.createLinkedHashMapCacheBuilder()
.expireAfterWrite(3600, TimeUnit.SECONDS)
.expireAfterAccess(1800, TimeUnit.SECONDS);
注意:expireAfterAccess 仅在本地缓存(EmbeddedCache)中可用,远程缓存和 MultiLevelCache 均不支持。多级缓存场景可以把 localExpire 设短一些以限制脏数据存活时间,但这仍是写入后固定过期,不能把过期语义模拟成“访问后滑动过期”。
09
Key 生成机制
裸用 Redis 时,key 的命名全靠自觉:"user:" + userId、"order_detail_" + orderId……不同开发者的风格五花八门,后期维护是噩梦。
JetCache 通过 KeyConvertor 和 SpEL 表达式统一解决这个问题:
// 简单参数
@Cached(name = "user:", key = "#userId")
User getUserById(Long userId);
// 嵌套属性
@Cached(name = "order:", key = "#order.userId + ':' + #order.orderId")
Order getOrderByUser(OrderQuery order);
// 条件缓存
@Cached(name = "product:", key = "#productId", condition = "#productId > 1000")
Product getProduct(Long productId);
// 后置条件:根据返回值决定是否缓存
@Cached(name = "vip:", key = "#userId", postCondition = "#result != null && #result.level > 1")
VipInfo getVipInfo(Long userId);
KeyConvertor 负责把 key 对象转成字符串。源码中提供了多种转换策略:
• fastjson2:使用 Fastjson2 序列化,可读性好,源码对应 Fastjson2KeyConvertor
• jackson:使用 Jackson 序列化,更安全,源码对应 JacksonKeyConvertor
• jackson3:Jackson 3.x 版本,源码对应 Jackson3KeyConvertor
• NONE:不做转换,直接使用 key 对象本身
2.7+ 默认 areaInCacheName=false,此时 key 格式是 {name}{convertedKey},比如 user:12345。只有显式配置 areaInCacheName: true 时,才会变成 {area}_{name}{convertedKey},比如 default_user:12345。
10
Value 序列化
远程缓存(Redis)需要序列化,JetCache 内置了多种序列化方案。可直接在 YAML 配置中使用的编码器:
| 序列化方式 | 源码类 | 优点 | 缺点 |
|---|---|---|---|
| java | JavaValueEncoder | JDK 内置,无需依赖 | 体积大,速度慢,需实现 Serializable |
| kryo | KryoValueEncoder / | 速度快,体积小 | 跨语言不支持;JetCache 实现未启用类注册 |
| kryo5 | Kryo5ValueEncoder | 基于 Kryo 5.x;2.8 起 | 同 kryo |
注:fastjson2(Fastjson2ValueEncoder)和 jackson3(Jackson3ValueEncoder)虽已实现,但默认未注册。因为 JSON 对 Java 对象的序列化兼容性不够好,官方不推荐作为通用编码器,仅在特殊场景下可以手动注册使用。
jetcache:
remote:
default:
valueEncoder: kryo
valueDecoder: kryo
生产环境推荐 kryo,兼顾性能和体积。自 2.8 起,kryo 和 kryo5 底层均使用 Kryo 5 实现。
11
反序列化安全:DecodeFilter 详解
JetCache 2.8 版本引入了重要的安全特性:DecodeFilter。这是一个反序列化过滤器,用于降低恶意构造的缓存数据触发反序列化攻击的风险。如果你用过 Fastjson 或 Log4j 的漏洞修复,应该对这个概念不陌生。
DecodeFilter 类采用了"默认拒绝 + 白名单 + 黑名单"的三重防护机制(关键代码示例如下):
public class DecodeFilter {
// 默认允许的包
public static final Set<String> DEFAULT_ALLOW_PATTERNS = Set.of(
"java.lang", // 只匹配 java.lang 包下的类(不含子包)
"java.util.", // 匹配 java.util 及其所有子包
"java.time.", // 时间相关类
"java.math", // 数学类
"java.net", // 网络类
"com.alicp.jetcache." // JetCache 内部类
);
// 默认拒绝的危险类(黑名单)
public static final Set<String> DEFAULT_DENY_PATTERNS = Set.of(
"java.lang.Runtime",
"java.lang.ProcessBuilder",
"javax.naming.", // JNDI 注入
"java.rmi.", // RMI 远程调用
"com.sun.", // JDK 内部类
// ... 更多已知的反序列化攻击类
);
}
白名单匹配规则有三种模式:
1. 前缀匹配(以 . 结尾):如 java.util. 匹配 java.util.HashMap 和 java.util.concurrent.ConcurrentHashMap
2. 精确匹配:如 java.lang.Runtime 只匹配这一个类
3. 包级匹配(不以 . 结尾且不是类名):如 java.lang 匹配 java.lang.String,但不匹配 java.lang.reflect.Proxy
如果你的业务类不在默认白名单里,相关缓存值的序列化或反序列化可能会失败并提示配置方法。需要手动添加:
jetcache:
decodeFilterAllowPatterns:
- com.yourcompany.dto.
- com.yourcompany.entity.
或通过代码配置:
DecodeFilter.getDefault().addAllowPatterns("com.yourcompany.");
黑名单优先级高于白名单,即使你把 java.lang. 加到白名单,java.lang.Runtime 仍然会被黑名单拦截。这是"安全优先"的设计原则。除非你非常清楚自己在做什么,否则不要删除默认的黑名单项。
12
多级缓存:JetCache 的杀手锏
这是 JetCache 最值得聊的功能。很多团队都知道本地缓存比 Redis 快,但自己搞多级缓存要解决的问题太多了:本地和远程的一致性怎么保证?本地缓存过期策略怎么设?更新时先更新哪个?
JetCache 的 CacheType.BOTH 一键解决:
@Cached(name = "user:", key = "#userId",
expire = 3600, // 远程缓存过期 1 小时
localExpire = 300, // 本地缓存过期 5 分钟
localLimit = 100, // 本地缓存最多 100 个元素
cacheType = CacheType.BOTH,
syncLocal = true) // 更新后广播失效其他 JVM 的本地缓存
User getUserById(Long userId);
工作机制:
• 读取顺序:本地缓存 → 远程缓存 → 数据源
• 写入顺序:按层级写入本地和远程(通常先本地后远程),两层写入不是原子操作
• 本地缓存更短过期时间:常见做法是把 localExpire 设为 expire 的 1/10~1/5,但具体比例要结合一致性要求和回源成本评估
更妙的是跨 JVM 本地缓存同步。BroadcastManager 抽象类定义了广播机制(简化示意):
public abstract class BroadcastManager implements AutoCloseable {
private final String sourceId = UUID.randomUUID().toString(); // 每个节点唯一标识
public abstract CacheResult publish(CacheMessage cacheMessage); // 发布消息
public abstract void startSubscribe(); // 订阅消息
protected void processCacheMessage(CacheMessage cacheMessage) {
if (sourceId.equals(cacheMessage.getSourceId())) {
return; // 忽略自己发出的消息
}
// 清除本地缓存
for (Cache c : caches) {
if (c instanceof AbstractEmbeddedCache) {
((AbstractEmbeddedCache) c).__removeAll(keys);
}
}
}
}
配置 broadcastChannel 后,当某个节点更新或删除缓存,会通过 Redis Pub/Sub 发广播消息,其他节点收到后自动清除对应的本地缓存。你不用自己写任何 Pub/Sub 代码。两点注意:广播只对 cacheType = CacheType.BOTH 且 syncLocal = true 的缓存生效(syncLocal 默认是 false);Redis Pub/Sub 是 at-most-once 投递,节点重启或漏收消息时不会补发,所以它只是加速本地失效的手段,不能当强一致保证,localExpire 仍要合理设置。
jetcache:
remote:
default:
type: redis.lettuce
broadcastChannel: myApp # 开启广播后,还需 cacheType=BOTH + syncLocal=true
13
自动刷新:后台定时刷新
有些场景,希望热点数据尽量不要过期——比如每日统计数据、系统配置。但又不想写定时任务去刷新。JetCache 的 @CacheRefresh 解决这个问题:
@Cached(name = "config:", key = "#key", expire = 3600)
@CacheRefresh(refresh = 1800, // 每 30 分钟刷新一次
stopRefreshAfterLastAccess = 7200) // 2 小时无人访问则停止刷新
String getConfig(String key);
源码中 RefreshPolicy 类定义了刷新策略的三个核心参数:
public class RefreshPolicy implements Cloneable {
private long refreshMillis; // 刷新间隔
private long stopRefreshAfterLastAccessMillis; // 无人访问后停止刷新
private long refreshLockTimeoutMillis = 60 * 1000; // 刷新锁超时时间
}
RefreshCache 类实现了自动刷新的核心逻辑,内部维护了一个任务映射表(简化示意):
public class RefreshCache<K, V> extends LoadingCache<K, V> {
private ConcurrentHashMap<Object, RefreshTask> taskMap = new ConcurrentHashMap<>();
class RefreshTask implements Runnable {
@Override
public void run() {
// 检查是否超过 stopRefreshAfterLastAccess
if (lastAccessTime + stopRefreshMillis < now) {
cancel(); // 停止刷新任务
return;
}
// 执行刷新
load();
}
}
}
工作原理:
1. 缓存被访问时,JetCache 为这个 key 启动后台刷新任务
2. 任务按 refresh 固定间隔周期执行(内部用 scheduleWithFixedDelay 调度),与剩余 TTL 无关
3. 刷新期间,旧数据继续可用,请求无感知
4. 如果 stopRefreshAfterLastAccess 时间内没人访问,停止刷新任务,节省资源
对于远程缓存,刷新时会尝试用分布式锁减少多节点重复刷新:
private void externalLoad(Cache concreteCache, long currentTime) {
byte[] lockKey = combine(newKey, LOCK_KEY_SUFFIX); // 加锁 key
boolean lockSuccess = concreteCache.tryLockAndRun(lockKey, loadTimeOut, TimeUnit.MILLISECONDS, () -> {
load();
concreteCache.put(timestampKey, String.valueOf(System.currentTimeMillis()));
});
}
这样,持续有访问的热点数据通常能被及时续期,冷数据也不会浪费刷新资源。但刷新是尽力而为:刷新失败、加载抛异常或任务停止后,数据仍会过期,需要回源重新加载,不能假设“永不过期”。
14
穿透保护:防止缓存击穿
高并发场景下,如果某个热点 key 突然失效,大量请求会同时回源到数据库,瞬间打垮后端,这就是缓存击穿。JetCache 的 @CachePenetrationProtect 解决这个问题:
@Cached(name = "hotItem:", key = "#itemId", expire = 300)
@CachePenetrationProtect(timeout = 3) // 等待超时 3 秒
Item getHotItem(Long itemId);
源码中 CacheConfig 类定义了穿透保护的配置项:
public class CacheConfig<K, V> implements Cloneable {
private boolean cachePenetrationProtect = false;
private Duration penetrationProtectTimeout = null; // 等待超时时间
}
AbstractCache 的 computeIfAbsentImpl 方法实现了穿透保护的核心逻辑(简化示意):
static <K, V> V computeIfAbsentImpl(...) {
CacheGetResult<V> r = cache.GET(key);
if (r.isSuccess()) {
return r.getValue();
}
if (cache.config().isCachePenetrationProtect()) {
// 同步加载:只让一个线程去加载,其他线程等待
loadedValue = synchronizedLoad(cache.config(), abstractCache, key, newLoader, cacheUpdater);
} else {
// 无保护:所有线程都可能穿透
loadedValue = newLoader.apply(key);
cacheUpdater.accept(loadedValue);
}
return loadedValue;
}
synchronizedLoad 方法使用 ConcurrentHashMap 和 CountDownLatch 实现了精巧的等待机制(简化示意):
static <K, V> V synchronizedLoad(...) {
ConcurrentHashMap<Object, LoaderLock> loaderMap = abstractCache.initOrGetLoaderMap();
LoaderLock ll = loaderMap.computeIfAbsent(lockKey, k -> {
LoaderLock lock = new LoaderLock();
lock.signal = new CountDownLatch(1);
lock.loaderThread = Thread.currentThread();
return lock;
});
if (ll.loaderThread == Thread.currentThread()) {
// 当前线程负责加载
try {
V loadedValue = newLoader.apply(key);
cacheUpdater.accept(loadedValue);
return loadedValue;
} finally {
ll.signal.countDown(); // 唤醒等待的线程
loaderMap.remove(lockKey);
}
} else {
// 其他线程加载中,等待结果
ll.signal.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
return ll.value;
}
}
原理:当缓存失效时,JetCache 在单个 JVM 内、对同一个 key 只允许一个线程去加载数据,其他线程等待加载完成后直接获取结果。注意保护范围:它是实例级的,不跨节点(集群里每个 JVM 仍会各回源一次);等待超时的线程也会自己回源。它减轻的是单机内同一 key 的并发回源压力,不是全局串行化。
还有一个相关配置 cacheNullValue:
@Cached(name = "user:", key = "#email", cacheNullValue = true)
User getUserByEmail(String email);
当查询结果为 null 时,也在缓存里存一个占位符,防止恶意请求用不存在的 key 反复穿透。
两者区别:
• @CachePenetrationProtect:防并发,一个线程加载,其他等待
• cacheNullValue:防穿透,把 null 也缓存起来
两者解决的是不同问题,按需开启:回源并发高就开 @CachePenetrationProtect;存在大量查询不存在 key 的流量才开 cacheNullValue,同时注意占位符对缓存容量的占用。
15
分布式锁:基于缓存实现
JetCache 还提供了一个意想不到的功能:基于缓存实现的分布式锁。源码中 Cache 接口定义了 tryLock 和 tryLockAndRun 方法:
default AutoReleaseLock tryLock(K key, long expire, TimeUnit timeUnit) {
final String uuid = UUID.randomUUID().toString();
// 使用 PUT_IF_ABSENT 实现原子加锁
CacheResult lockResult = cache.PUT_IF_ABSENT(key, uuid, expire, timeUnit);
if (lockResult.isSuccess()) {
return () -> {
// 解锁时删除 key
cache.REMOVE(key);
};
}
return null; // 获取锁失败
}
default boolean tryLockAndRun(K key, long expire, TimeUnit timeUnit, Runnable action) {
try (AutoReleaseLock lock = tryLock(key, expire, timeUnit)) {
if (lock != null) {
action.run();
return true;
}
return false;
}
}
源码中的实现比这更复杂,包含了重试机制和"查询确认"逻辑,防止网络抖动导致的误判。CacheConfig 中定义了相关参数:
private int tryLockUnlockCount = 2; // 解锁重试次数
private int tryLockInquiryCount = 1; // 查询确认次数
private int tryLockLockCount = 2; // 加锁重试次数
使用方式非常简洁:
// 方式一:手动管理
try (AutoReleaseLock lock = cache.tryLock("myLock", 10, TimeUnit.SECONDS)) {
if (lock != null) {
// 获取锁成功,执行业务逻辑
}
}
// 方式二:一行搞定
cache.tryLockAndRun("myLock", 10, TimeUnit.SECONDS, () -> {
// 执行业务逻辑
});
注意:MultiLevelCache 自身不实现锁算法,它的 tryLock/tryLockAndRun 会委托给最后一级缓存(通常是远程缓存)执行,实际是否为分布式锁取决于底层实现。
16
声明式缓存注解详解
JetCache 提供了三个核心注解,覆盖缓存的生命周期管理。
@Cached:声明缓存方法,查询时自动缓存结果
@Cached(name = "user:", key = "#userId", expire = 3600,
cacheType = CacheType.BOTH, localExpire = 300,
cacheNullValue = true, condition = "#userId > 0")
User getUserById(Long userId);
@CacheUpdate:更新缓存,方法执行后自动更新对应的缓存
@CacheUpdate(name = "user:", key = "#user.userId", value = "#user")
void updateUser(User user);
@CacheInvalidate:删除缓存,方法执行后自动删除对应的缓存
@CacheInvalidate(name = "user:", key = "#userId")
void deleteUser(Long userId);
// 批量删除
@CacheInvalidate(name = "user:", key = "#userIds", multi = true)
void deleteUsers(List<Long> userIds);
注解支持 @Repeatable,一个方法可以配置多个删除操作:
@CacheInvalidate(name = "user:", key = "#userId")
@CacheInvalidate(name = "userDetail:", key = "#userId")
void deleteUser(Long userId);
17
CacheLoader:自定义加载逻辑
源码中 CacheLoader 接口定义了数据加载的契约:
@FunctionalInterface
public interface CacheLoader<K, V> extends Function<K, V> {
V load(K key) throws Throwable; // 加载单个值
default Map<K, V> loadAll(Set<K> keys) throws Throwable { // 批量加载
Map<K, V> map = new HashMap<>();
for (K k : keys) {
map.put(k, load(k));
}
return map;
}
default boolean vetoCacheUpdate() { // 是否阻止缓存更新
return false;
}
}
使用示例:
QuickConfig qc = QuickConfig.newBuilder("product")
.loader((CacheLoader<Long, Product>) key -> productMapper.selectById(key))
.build();
Cache<Long, Product> cache = cacheManager.getOrCreateCache(qc);
// 自动加载:缓存不存在时自动调用 loader
Product product = cache.get(productId); // 无需手动判断
18
监控统计
JetCache 内置了监控统计功能。DefaultCacheMonitor 类实现了 CacheMonitor 接口,它会收集以下指标:
public class CacheStat {
// Get 操作统计
long getCount; // 总查询次数
long getHitCount; // 命中次数
long getMissCount; // 未命中次数
long getFailCount; // 失败次数
long getExpireCount; // 过期次数
long getTimeSum; // 总耗时
// 计算方法
public double hitRate() { return getCount == 0 ? 0 : 1.0 * getHitCount / getCount; }
public double qps() { long duration = statEndTime - statStartTime; return duration == 0 ? 0 : 1000.0 * getCount / duration; }
public double avgGetTime() { return getCount == 0 ? 0 : 1.0 * getTimeSum / getCount; }
}
通过 CacheManager 获取统计信息(需要预先创建并注册 DefaultCacheMonitor 实例):
DefaultCacheMonitor monitor = new DefaultCacheMonitor("userCache");
// 通过 CacheBuilder.addMonitor(monitor) 或 CacheConfig.setMonitors() 注册
CacheStat stat = monitor.getCacheStat();
System.out.println("命中率: " + stat.hitRate());
System.out.println("QPS: " + stat.qps());
配置文件中开启定期打印:
jetcache:
statIntervalMinutes: 15 # 每 15 分钟打印一次统计信息
通过监控数据,你可以发现缓存配置是否合理:命中率太低可能需要调整过期时间,QPS 过高可能需要增加本地缓存。
19
编程式 API
除了声明式注解,JetCache 还提供了完整的编程式 API,适合需要精细控制的场景。通过 CacheManager 和 QuickConfig 创建缓存实例:
@Service
public class UserService {
@Autowired
private CacheManager cacheManager;
private Cache<Long, User> userCache;
@PostConstruct
public void init() {
QuickConfig qc = QuickConfig.newBuilder("user")
.expire(Duration.ofHours(1))
.localExpire(Duration.ofMinutes(5))
.cacheType(CacheType.BOTH)
.localLimit(100)
.penetrationProtect(true)
.cacheNullValue(true)
.build();
userCache = cacheManager.getOrCreateCache(qc);
}
public User getUser(Long userId) {
return userCache.computeIfAbsent(userId, id -> userMapper.selectById(id));
}
public void updateUser(User user) {
userMapper.updateById(user);
userCache.put(user.getId(), user);
}
public void deleteUser(Long userId) {
userMapper.deleteById(userId);
userCache.remove(userId);
}
}
上面的更新/删除是简化示例:put/remove 失败不会抛异常(结果被忽略),数据库和缓存之间也没有事务保证,并发下 put 还可能把旧值写回缓存。生产上建议改成"先更新库、再失效缓存"(@CacheInvalidate),必要时用短 TTL 兜底。
20
异步 API:配合 Lettuce 发挥最大性能
JetCache 支持异步操作,配合 Lettuce 客户端效果最佳。所有大写方法返回的 CacheResult 都可以通过 future() 拿到 CompletionStage<ResultData>,在结果就绪时触发回调:
// 异步获取:回调触发后再从 result 读值
CacheGetResult<User> result = cache.GET(userId);
result.future().thenRun(() -> {
if (result.isSuccess()) {
User user = result.getValue();
// 处理缓存值
} else if (result.getResultCode() == CacheResultCode.FAIL) {
// 缓存访问失败
}
});
// 异步写入:future 完成只代表操作有结果,是否成功要看 resultCode
CacheResult putResult = cache.PUT(userId, user);
putResult.future().thenRun(() -> {
if (putResult.isSuccess()) {
log.info("缓存写入成功");
}
});
注意:只有 Lettuce 实现真正支持异步。Jedis 等其他客户端的大写异步方法内部仍是同步阻塞执行,只是返回兼容的 CacheResult 对象,拿不到异步收益。所以要发挥异步 API 的性能,用 jetcache-starter-redis-lettuce。
21
与 Spring Cache 的对比
Spring 自带的 @Cacheable 也能做声明式缓存,为什么还要用 JetCache?
| 功能 | Spring Cache | JetCache |
|---|---|---|
| 多级缓存 | 需手动实现 | 原生支持( |
| TTL 过期时间 | 配置复杂 | 注解原生支持( |
| 自动刷新 | 不支持 | @CacheRefresh |
| 穿透保护 | 有限( | @CachePenetrationProtect |
| 本地缓存同步 | 不支持 | broadcastChannel |
| 异步 API | Spring 6.1+ 支持( | future() ( |
| 分布式锁 | 不支持 | tryLock 、 |
| 统计监控 | 可借 Micrometer/Actuator | 内置 |
| 编程式 API | Cache/CacheManager 接口 | 注解 + API 双模式 |
简单说:两者的差别不在"谁能做的更多",而在于 JetCache 把多级缓存、TTL、自动刷新、并发保护和统计这些高频需求做成了开箱即用的注解,Spring Cache 则是更通用、生态更大的抽象。按团队需求选择即可。
值得一提的是,JetCache 的编程式 API 和声明式注解可以混用。同一个 cache 实例,既可以通过注解自动管理,也可以在代码中手动操作。这在某些复杂业务场景下非常实用:注解处理常规的增删改查,编程式 API 处理特殊的批量操作或条件更新。
22
Spring Boot 集成:三步搞定
第一步,加依赖:
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis-lettuce</artifactId>
<version>2.8.0.RC</version>
</dependency>
第二步,启动类加注解:
@SpringBootApplication
@EnableMethodCache(basePackages = "com.yourcompany.service")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第三步,写 YAML 配置:
jetcache:
statIntervalMinutes: 15
local:
default:
type: caffeine
keyConvertor: fastjson2
limit: 100
remote:
default:
type: redis.lettuce
keyConvertor: fastjson2
valueEncoder: kryo
valueDecoder: kryo
broadcastChannel: myApp
uri: redis://127.0.0.1:6379/0
版本选择:JetCache 2.7.x 支持 Java 8 + Spring Boot 2.x(Spring Boot 3 从 2.7.4 起支持);2.8.x 需要 Java 17,支持 Spring Boot 3.x/4.x。注意 2.8 目前只有 2.8.0.RC 预发布版,与 2.7 不兼容,求稳可以先用 2.7.x 稳定版。
23
什么时候该用,什么时候不该用
适合用的场景:
• 读多写少的业务数据(用户信息、商品详情、配置项)
• 需要本地缓存加速的热点数据
• 需要自动刷新的统计数据
• 团队希望统一缓存规范,减少重复代码
• 需要监控缓存命中率、QPS 等指标
不太适合的场景:
• 需要严格分布式锁的场景(用 Redisson 或 ZooKeeper 更合适)
• 缓存逻辑非常复杂,注解表达不了的(但可以用编程式 API)
• 项目极小,引入框架反而增加复杂度
24
踩坑提醒
1. 同类方法调用注解不生效:Spring AOP 的老问题,this.methodB() 不会走代理。解法是自注入或把方法拆到不同类。
2. 编译参数:注解里用参数名(如 #userId)需要加 -parameters 编译参数。
3. 本地缓存容量:localLimit 别设太大,本地缓存吃 JVM 堆内存。
4. 2.8 版本反序列化安全:默认启用过滤器,需配置白名单 decodeFilterAllowPatterns。
5. 多级缓存不支持 putIfAbsent:源码中明确抛出 UnsupportedOperationException,如果需要原子操作,直接用远程缓存。
6. 刷新锁超时:自动刷新默认锁超时 60 秒,如果数据加载很慢,需要调整 refreshLockTimeout。
25
性能调优建议
用好 JetCache,几个配置参数很关键:
本地缓存容量:localLimit 不是越大越好。本地缓存占用 JVM 堆内存,容量过大可能触发 Full GC。可以从热点数据量的 1.5~2 倍起步(经验值),再结合对象大小和堆内存调整。比如你的系统活跃用户约 5000 人,localLimit设为 8000~10000 通常够用。
本地缓存过期时间:localExpire 应该比 expire 短。这是有意为之的设计:本地缓存过期更快,能更及时地感知远程缓存的变化。经验比例是 1:10~1:5。比如远程缓存 1 小时,本地缓存设 5~10 分钟。
刷新时机:@CacheRefresh 的 refresh 是固定刷新间隔,要确保 refresh + 数据加载耗时 明显小于 expire,给刷新留出余量。比如数据加载需要 10 秒,refresh 至少设 30 秒以上,且 expire 要比 refresh 大足够多,否则可能出现上一轮刷新未完成、数据就已过期的情况。
穿透保护超时:@CachePenetrationProtect(timeout) 的超时时间要考虑数据加载耗时。如果超时时间短于加载时间,等待的线程会超时返回,然后自己去加载,穿透保护就失效了。
26
最后
JetCache 解决的不是"能不能用缓存"的问题,而是"怎么用缓存更省心"的问题。裸用 Redis 当然能干活,但就像手写 JDBC 也能干活一样,谁还愿意手写 SQL 呢?如果你的项目已经在用 Redis,且缓存逻辑开始变得零散和难以维护,JetCache 值得一试。它不会替代 Redis,但会让 Redis 用得更舒服。
245



被折叠的 条评论
为什么被折叠?



