Spring @Cacheable能否实现仅读取缓存而不写入缓存?
实现微服务仅读取缓存的解决方案
首先你之前的配置存在问题:
condition="false"会直接跳过整个缓存逻辑,既不读取缓存也不写入缓存,完全不符合需求;unless="true"理论上能实现“不写入缓存”,但缓存未命中时仍会执行方法逻辑,只是不把结果存入缓存。如果配置没生效,大概率是key的SpEL表达式写错了,比如没有正确引用方法参数。
下面给你两种可行的实现方式:
方式一:用@Cacheable实现“仅读缓存,绝不写入”
这种方式下,缓存命中时直接返回缓存值;缓存未命中时会执行方法逻辑,但不会把结果存入缓存。确保unless="true"配置正确,同时检查key表达式的合法性:
@Cacheable(cacheNames = "test-stack", key = "#id", unless = "true") public SomeData getData(Long id) { // 缓存未命中时会执行这里的业务逻辑,但结果不会被存入缓存 return fetchDataFromDatabase(id); }
方式二:强制仅读缓存,缓存未命中时直接返回空/抛出异常
如果你的需求是完全不执行方法逻辑,只从缓存取数据,直接用@Cacheable无法实现,需要手动通过CacheManager读取缓存:
@Autowired private CacheManager cacheManager; public SomeData getData(Long id) { Cache cache = cacheManager.getCache("test-stack"); if (cache == null) { return null; } Cache.ValueWrapper valueWrapper = cache.get(id); return valueWrapper != null ? (SomeData) valueWrapper.get() : null; // 也可以在缓存未命中时抛出异常,比如: // throw new IllegalStateException("No cache found for id: " + id); }
另外要注意,两个微服务必须使用同一个缓存实例(比如Redis),并且缓存名称、序列化/反序列化方式保持一致,否则读取不到另一个服务写入的缓存数据。
内容的提问来源于stack exchange,提问作者Don_Quijote
相关产品推荐
相关产品推荐

