跳至内容
LoadUp Cache Component

LoadUp Cache Component

以 Spring Cache 标准门面(@Cacheable / @CacheEvict / @CachePut)提供缓存能力, 底层中间件(Caffeine / Redis / JetCache)通过 binder 热插拔。业务代码只写 Spring Cache 注解, 不依赖任何 LoadUp 缓存类 ;切换底层实现时业务代码零修改。

引入

先引入 loadup-framework-bom BOM(版本由 BOM 统一管理),业务模块依赖 api,集成方工程按需加 binder:

<dependency>
    <groupId>io.github.loadup-cloud</groupId>
    <artifactId>loadup-components-kv-api</artifactId>
</dependency>
<!-- 三选一,与 loadup.cache.type 对应 -->
<dependency>
    <groupId>io.github.loadup-cloud</groupId>
    <artifactId>loadup-components-kv-binder-caffeine</artifactId>
</dependency>
<dependency>
    <groupId>io.github.loadup-cloud</groupId>
    <artifactId>loadup-components-kv-binder-redis</artifactId>
</dependency>
<dependency>
    <groupId>io.github.loadup-cloud</groupId>
    <artifactId>loadup-components-kv-binder-jetcache</artifactId>
</dependency>

使用

@Cacheable(cacheNames = "product", key = "#id")
public Product getProduct(Long id) { ... }

@CachePut(cacheNames = "product", key = "#id")
public Product updateProduct(Long id, String name) { ... }

@CacheEvict(cacheNames = "product", key = "#id")
public void deleteProduct(Long id) { ... }

配置

loadup:
  cache:
    type: redis                     # caffeine(默认)/ redis / jetcache / none
    default-ttl: 30m                # 默认过期;不配置 = 永不过期
    caches:
      product:
        ttl: 5m
        random-expiration-range: 30s  # 随机过期防雪崩
        allow-null-values: false      # 默认 true
# binder 特有配置
# redis:   loadup.cache.binder.redis.key-prefix
# caffeine: loadup.cache.binder.caffeine.maximum-size
# jetcache: loadup.cache.binder.jetcache.default-cache-type (LOCAL/REMOTE/BOTH)
#           loadup.cache.binder.jetcache.sync-local / penetration-protect / remote-key-prefix

能力矩阵(契约)

能力 Spring Cache 注解 caffeine redis jetcache
读/写/更新 @Cacheable @CachePut ✓ ✓ ✓
失效 @CacheEvict(单键/全清) ✓ ✓ ✓
空值缓存 allow-null-values ✓ ✓ ✓
按 cache 名 TTL loadup.cache.caches.*.ttl ✓ ✓ ✓
随机过期防雪崩 random-expiration-range ✓ ✓ ✓
本地/分布式/多级 type 本地 分布式 多级(可选同步)
防击穿/防穿透 JetCache 特有 ✗ ✗ penetration-protect

集成方只承诺 ✓ 的能力;切换 binder 零代码修改的前提是业务只用契约内能力。

实现与决策

设计决策、内部结构、序列化选择见 ARCHITECTURE.md。

许可证

Apache License 2.0 (Apache-2.0)


设计与实现

1. 设计定位

LoadUp Cache 的 facade 就是 Spring Cache 标准门面:业务代码只用 @Cacheable / @CacheEvict / @CachePut,不 import 任何 LoadUp 缓存类。LoadUp 只补三类 Spring Cache 表达不了的增量: 按 cache name 的 TTL、空值缓存开关、随机过期(防雪崩)。底层中间件 (Caffeine / Redis / JetCache)全部以 binder 形式提供,集成方通过 pom 依赖 + 一个配置项切换, 业务代码零修改。

2. 架构图

业务代码(@Cacheable / @CacheEvict / @CachePut)
        │
        ▼
Spring Cache 抽象(CacheManager / Cache 接口)          ← 标准门面
        │
        ▼
loadup-components-cache-api(LoadupCacheProperties + CacheJsonCodec + 防雪崩语义)
        │                        │
        ├── binder-caffeine ─────┤  LoadupCaffeineCacheManager(Caffeine Expiry 实现 TTL/抖动)
        ├── binder-redis ────────┤  RedisCacheManager + GenericJacksonJsonRedisSerializer
        └── binder-jetcache ─────┘  JetCacheSpringCacheManager(本地 Caffeine + 可选 Redis 远程)
  • loadup.cache.type 与 binder 自动配置的 @ConditionalOnProperty 绑定:classpath 上有哪个 binder jar,配成对应 type 即生效(caffeine 为 matchIfMissing 默认)。
  • 三个 binder 均注册 @ConditionalOnMissingBean(CacheManager.class),集成方想完全接管时 可自定义 CacheManager 覆盖。

3. 关键设计决策

3.1 序列化:JSON + @class 类型标记(弃用 JDK 序列化)

统一采用 JSON 序列化,实现为共享的 CacheJsonCodec(api 模块):

  • JDK 序列化的缺陷:要求所有缓存对象实现 Serializable;本项目 DTO 强制使用 Java record (不可序列化);载荷大(含类元数据);反序列化是安全攻击面。
  • JSON 方案:业务类型保持普通 record/POJO;写值时用应用 ObjectMapper 的副本(不改全局 mapper)并启用 activateDefaultTypingAsProperty(NON_FINAL_AND_RECORDS, "@class"),读回时恢复具体类型 (final record 也能往返)。由于缓存 API 必须支持集成方任意业务类型,codec 使用允许所有子类型的 显式校验器;因此缓存数据必须来自可信存储,不能将不可信 JSON 直接交给该 codec 反序列化。
  • Spring Cache 的 null 值标记 NullValue 是空 bean,Jackson 默认无法序列化;codec 内注册 专用 NullValueSerializer,写出 {"@class":"..."}、读回仍是 NullValue,与 Spring Data Redis 的 GenericJacksonJsonRedisSerializer null-value 行为一致。
  • Redis binder 直接复用 codec 的 typed mapper 构造 GenericJacksonJsonRedisSerializer (注意:必须传带类型标记的 mapper,否则 @class 不生效、具体类型退化为 Map)。

3.2 Redis binder:同步写保证 Spring Cache 契约

Spring Data Redis 4.x 在 Lettuce(同时实现同步/响应式工厂)下默认启用 异步写: put / evict / clear 变成 fire-and-forget,@CachePut 后立即 @Cacheable 读可能读到旧值, clear() 后立刻读也可能命中残留。binder 显式构造 RedisCacheWriter.create(connectionFactory, c -> c.immediateWrites(true)) 恢复同步语义,保证"写后立即可读"。

3.3 JetCache binder:薄适配,不引入注解体系

  • 不用 JetCache 自己的 @Cached 注解体系,只把它当底层引擎:JetCacheSpringCacheManager 按 cache name 生成 QuickConfig,JetCacheSpringCache 实现 Spring Cache 接口 (get(key, Callable) 走 JetCache computeIfAbsent)。
  • 远程 key 设计:<remoteKeyPrefix><cacheName>::<key>(keyConvertor 加 :: 前缀、远程层加 全局前缀),clear() 用 SCAN 匹配 loadup:cache:<name>::* 批量删除。
  • 远程层仅当 classpath 存在 RedisConnectionFactory 时装配 → LOCAL 模式不依赖 Redis。
  • 本地层默认 Caffeine,sync-local 开启时本地失效会推送到远程通道,多实例本地缓存一致。

3.4 防雪崩:统一随机过期语义

RandomExpiration.apply(base, range) 是三个 binder 共用的 TTL 抖动算法 (base + random[0, range])。Caffeine 用 Expiry、Redis 用 RedisCacheWriter.TtlFunction、 JetCache 用每次写入的 expire 参数,保证同一配置在不同底层行为一致。

4. 扩展点:新增 binder

  1. 新建 loadup-components-cache-binder-{impl},只依赖 -api;
  2. 提供 CacheManager bean + @ConditionalOnProperty(prefix="loadup.cache", name="type", havingValue="{type}"),并在 META-INF/spring/...AutoConfiguration.imports 注册;
  3. TTL / 空值 / 随机过期必须复用 api 的 LoadupCacheProperties 与 RandomExpiration;
  4. 在 -test 的 AbstractCacheBinderIT 加一个子类跑同一套契约测试。

5. 反绕过契约(防止直接对接中间件)

约束 执行方式
业务模块只依赖 -cache-api binder 坐标只在集成方工程/-test 出现;BOM 单点管理版本
业务代码只用 Spring Cache 注解 CacheJsonCodec / JetCache 适配不暴露给业务;API 层不提供手写 CRUD 门面
切 binder 零代码修改 AbstractCacheBinderIT 同一业务服务在 caffeine/redis/jetcache 上跑同一套用例
中间件 API 不泄漏 binder 的配置走 loadup.cache.* / loadup.cache.binder.*,不要求业务感知实现细节

6. 测试

  • AbstractCacheBinderIT:统一契约(读/写/失效/全清/空值/TTL/随机过期 + CacheManager 类型断言)。
  • CaffeineCacheIT / RedisCacheIT(Testcontainers Redis)/ JetCacheLocalCacheIT / JetCacheBothCacheIT(Testcontainers Redis,BOTH 多级)。
  • RandomExpirationTest:抖动边界与语义。