登录
首页 >  文章 >  java教程

Spring缓存:方法结果写入多个缓存技巧

时间:2026-05-14 17:36:42 253浏览 收藏

本文深入探讨了在Spring应用中如何巧妙结合@Cacheable注解与手动CacheManager操作,实现一次业务方法调用即可将同一实体(如Identifiers)自动同步写入多个不同维度的缓存(例如同时按customerId和accountNumber缓存),从而彻底避免重复远程调用、提升多入口查询的缓存命中率,并保障数据一致性;方案简洁可靠、无需复杂事件或异步机制,兼顾可读性、生产可用性与扩展性,是应对多唯一标识实体缓存场景的高效实践。

Spring Caching:如何将一个方法的返回结果同时写入多个缓存

本文详解如何在 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 缓存代理机制,也无需引入复杂事件或异步逻辑。

? 步骤实现

  1. 定义两个独立缓存名称(需在 application.yml 或 @EnableCaching 配置中声明):

    spring:
    cache:
     type: simple # 或 redis/caffeine 等
  2. 注入 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"));
     }
  3. 为每个入口方法添加 @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 / 手机号 / 邮箱、订单号 / 外部交易号等),是提升缓存命中率与系统响应性能的关键实践。记住:缓存设计的核心不是“能存”,而是“存得巧、取得准、失效稳”。

今天关于《Spring缓存:方法结果写入多个缓存技巧》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>