
Spring 的 @Cacheable 默认只写入一个缓存,但可通过手动注入 CacheManager 并在方法中显式调用 cache.put(),实现在一次业务调用中将同一结果同步写入多个键值缓存(如按 customerId 和 accountNumber 双索引)。
spring 的 `@cacheable` 默认只写入一个缓存,但可通过手动注入 `cachemanager` 并在方法中显式调用 `cache.put()`,实现在一次业务调用中将同一结果同步写入多个键值缓存(如按 `customerid` 和 `accountnumber` 双索引)。
在微服务或高并发场景中,常需通过不同维度(如客户 ID、账号、手机号等)快速检索同一实体。以 Identifiers 为例,它同时包含 customerId(Long)和 accountNumber(String),理想情况下:一次远程调用获取结果后,应自动填充两个缓存——既支持按 ID 查,也支持按账号查,且后续任一维度查询均命中缓存,避免重复耗时请求。
但 Spring 的 @Cacheable 是“单缓存单入口”设计:一个带注解的方法只能绑定一个缓存名与一个 key 表达式,无法原生实现“一写多存”。所幸,Spring 提供了灵活的底层抽象——CacheManager 和 Cache 接口,允许我们在业务逻辑中主动操作任意缓存实例。
✅ 推荐方案:@Cacheable + 手动 Cache.put()
核心思路是:
- 保留 @Cacheable 保障主路径的缓存读取与基础写入;
- 在方法体内,通过注入的 Cache 实例,额外写入另一缓存,确保双索引一致性。
以下是完整可运行示例:
@Service
@RequiredArgsConstructor
public class CachedIdentifiersCache {
private final Cache identifiersCacheByCustomerId;
private final Cache identifiersCacheByAccountNumber;
private final LazyIdentifiersService slowServiceWithMultipleRestInvocations;
// 构造器注入两个缓存实例(由 CacheManager 获取)
public CachedIdentifiersCache(CacheManager cacheManager,
LazyIdentifiersService service) {
this.slowServiceWithMultipleRestInvocations = service;
this.identifiersCacheByCustomerId =
Objects.requireNonNull(cacheManager.getCache("identifiers_cache_by_customer_id"));
this.identifiersCacheByAccountNumber =
Objects.requireNonNull(cacheManager.getCache("identifiers_cache_by_account_number"));
}
@Cacheable(value = "identifiers_cache_by_customer_id", key = "#customerId")
public Identifiers getCachedIdentifiers(Long customerId) {
Identifiers identifiers = slowServiceWithMultipleRestInvocations.getIdentifiers();
// ✅ 主缓存已由 @Cacheable 自动写入;此处手动补充 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 = slowServiceWithMultipleRestInvocations.getIdentifiers();
// ✅ 主缓存已由 @Cacheable 自动写入;此处手动补充 customerId 缓存
if (identifiers != null && identifiers.getCustomerId() != null) {
identifiersCacheByCustomerId.put(identifiers.getCustomerId(), identifiers);
}
return identifiers;
}
}
? 关键点说明:
- CacheManager.getCache("xxx") 安全获取已声明的缓存(需提前在配置中定义,如 @EnableCaching + @Bean CaffeineCacheManager);
- cache.put(key, value) 是线程安全操作,适用于大多数缓存实现(Caffeine、ConcurrentMap、RedisCache 等);
- null 检查防止空指针,同时避免向缓存写入无效数据。
⚠️ 注意事项与进阶建议
线程安全与重复计算风险:若多个线程几乎同时用不同键(如 customerId=123 和 accountNumber="A001")触发首次加载,可能造成 slowServiceWithMultipleRestInvocations 被执行多次。此时可结合 @Cacheable(sync = true)(仅限基于 ConcurrentMapCache 等支持同步的缓存)或使用分布式锁(如 RedisLock)控制首次加载的排他性。
缓存一致性维护:当 Identifiers 内容变更(如账户迁移),需同步清理两个缓存。建议封装 evictByIdAndAccount(Long id, String account) 方法,统一调用 cache.evict()。
-
替代方案对比:
- ❌ @CachePut 组合:不可行,因 Spring AOP 代理限制,@Cacheable 方法内无法直接调用本类另一个 @CachePut 方法;
- ❌ 同一方法多注解:@Cacheable 与 @CachePut 不能共存于同一方法;
- ✅ 封装 Cache 工具类:可进一步抽象为 DualIndexCacheWriter
,提升复用性与测试性。
✅ 总结
Spring Cache 本身不提供“一写多存”的声明式语法,但通过 CacheManager + 显式 put() 的组合,能以低侵入、高可控的方式实现双索引缓存。该方案简洁可靠,适用于绝大多数本地/分布式缓存场景,是解决多维查询缓存问题的推荐实践。










