
本文详解如何在 Spring 中通过 @Cacheable 结合手动 CacheManager 操作,实现在一次方法调用中将同一业务对象(如 Identifiers)自动同步写入多个键维度的缓存(如按 customerId 和 accountNumber 分别缓存),避免重复远程调用并保证多入口缓存一致性。
本文详解如何在 spring 中通过 `@cacheable` 结合手动 `cachemanager` 操作,实现在一次方法调用中将同一业务对象(如 `identifiers`)自动同步写入多个键维度的缓存(如按 `customerid` 和 `accountnumber` 分别缓存),避免重复远程调用并保证多入口缓存一致性。
在基于 Spring 的微服务开发中,常遇到「一个实体可通过多种唯一标识查询」的场景——例如客户信息既可通过 customerId(Long 类型)获取,也可通过 accountNumber(String 类型)获取。理想情况下,无论首次调用是通过哪种方式触发,都应将完整结果(如 Identifiers 对象)同时写入两个独立缓存,后续任一维度查询均可命中缓存,彻底规避重复的慢速远程调用(如多次 REST 请求)。但 Spring 原生 @Cacheable 仅支持单缓存写入,无法直接实现“一写双存”。本文提供一种简洁、可靠且生产就绪的解决方案。
✅ 核心思路:@Cacheable + 手动 CacheManager 写入
我们保留 @Cacheable 负责主缓存逻辑(自动缓存 + 缓存穿透防护),再通过注入的 CacheManager 主动向另一个关联缓存写入相同结果。这种方式不破坏 Spring AOP 缓存代理机制,也无需引入复杂事件或异步逻辑。
? 步骤实现
-
定义两个独立缓存名称(需在 application.yml 或 @EnableCaching 配置中声明):
spring: cache: type: simple # 或 redis/caffeine 等
-
注入 CacheManager 并预取两个 Cache 实例:
@Service @RequiredArgsConstructor public class CachedIdentifiersCache { private final Cache identifiersCacheByCustomerId; private final Cache identifiersCacheByAccountNumber; private final LazyIdentifiersService slowService; public CachedIdentifiersCache(CacheManager cacheManager, LazyIdentifiersService slowService) { this.slowService = slowService; this.identifiersCacheByCustomerId = Objects.requireNonNull(cacheManager.getCache("identifiers_cache_by_customer_id")); this.identifiersCacheByAccountNumber = Objects.requireNonNull(cacheManager.getCache("identifiers_cache_by_account_number")); } -
为每个入口方法添加 @Cacheable,并在方法体内手动填充对端缓存:
@Cacheable(value = "identifiers_cache_by_customer_id", key = "#customerId") public Identifiers getCachedIdentifiers(Long customerId) { Identifiers identifiers = slowService.getIdentifiersByCustomerId(customerId); // ✅ 主动写入 accountNumber 缓存 if (identifiers != null && identifiers.getAccountNumber() != null) { identifiersCacheByAccountNumber.put(identifiers.getAccountNumber(), identifiers); } return identifiers; } @Cacheable(value = "identifiers_cache_by_account_number", key = "#accountNumber") public Identifiers getCachedIdentifiers(String accountNumber) { Identifiers identifiers = slowService.getIdentifiersByAccountNumber(accountNumber); // ✅ 主动写入 customerId 缓存 if (identifiers != null && identifiers.getCustomerId() != null) { identifiersCacheByCustomerId.put(identifiers.getCustomerId(), identifiers); } return identifiers; } }
? 注意:slowService 的两个方法(getIdentifiersByCustomerId / getIdentifiersByAccountNumber)应根据入参实际构造或查询完整的 Identifiers 对象(含 customerId 和 accountNumber),这是双写成功的前提。
⚠️ 关键注意事项
线程安全性:上述方案在高并发下可能出现「两次缓存未命中 → 两次远程调用」问题(即缓存击穿)。若需强一致性,可启用 @Cacheable(sync = true)(仅限 ConcurrentMapCache 等支持同步的缓存实现),或结合分布式锁(如 RedisLock)控制首次加载。
空值处理:务必检查 identifiers 及其字段(如 getCustomerId())是否为 null,避免向缓存写入 null 键或值(部分缓存实现会抛异常)。
-
缓存更新与失效:当 Identifiers 数据变更时,需同步清理两个缓存(可用 @CacheEvict 多缓存指定):
@CacheEvict(allEntries = true, value = {"identifiers_cache_by_customer_id", "identifiers_cache_by_account_number"}) public void evictAllCaches() { } -
替代方案对比:
- ❌ @CachePut 组合:因 Spring AOP 代理限制,@Cacheable 方法内无法直接调用本类 @CachePut 方法;
- ❌ 同一方法双 @Cacheable:不被支持;
- ✅ CacheManager 手动操作:最直接、可控、无侵入性,推荐首选。
✅ 总结
通过将 @Cacheable 与 CacheManager 显式操作结合,你可以在保持 Spring 缓存语义清晰的前提下,优雅实现「一次计算、双缓存写入」。该模式适用于所有具备多唯一键映射关系的实体(如用户 ID / 手机号 / 邮箱、订单号 / 外部交易号等),是提升缓存命中率与系统响应性能的关键实践。记住:缓存设计的核心不是“能存”,而是“存得巧、取得准、失效稳”。










