You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免在Redis缓存中缓存Null值?(注解缓存场景)

解决@CacheResult缓存时不存入Null值的方案

先提下原代码的两处小问题:方法名geteEmployee应为getEmployee,cacheName的引号未闭合,正确写法是@CacheResult(cacheName = "testCache")。针对返回Null时不存入缓存的需求,有以下实用方案:

  • 方案一:改用@CachePut配合条件判断
    @CacheResult无法直接添加缓存过滤条件,而@CachePut支持通过condition属性指定缓存触发规则。修改后的代码如下:

    @CachePut(cacheName = "testCache", key = "#empId", condition = "#result != null")
    public Employee getEmployee(String empId) {
        // 业务逻辑
        return employee;
    }
    

    其中condition = "#result != null"表示仅当方法返回值不为Null时,才将结果存入testCache缓存,键值使用empId。

  • 方案二:自定义缓存条目过滤器(全局/局部生效)
    若需全局统一处理Null值过滤,可自定义JCache(JSR-107)的CacheEntryFilter接口实现类:

    public class NonNullCacheEntryFilter<K, V> implements CacheEntryFilter<K, V> {
        @Override
        public boolean evaluate(CacheEntry<? extends K, ? extends V> entry) {
            // 仅保留非Null的缓存条目
            return entry.getValue() != null;
        }
    }
    

    之后可在@CacheResult注解中指定该过滤器,局部生效:

    @CacheResult(cacheName = "testCache", filter = NonNullCacheEntryFilter.class)
    public Employee getEmployee(@CacheKey String empId) {
        // 业务逻辑
        return employee;
    }
    

    也可在缓存配置中全局绑定该过滤器,实现所有缓存统一过滤Null值。

内容的提问来源于stack exchange,提问作者Geeks For geeks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 22:24:22