3. Spring-boot 整合缓存服务之Redis 使用遇到的问题及解决方案

本文概述了在Spring Boot中使用Redis缓存时遇到的两个常见问题:@Cacheable注解失效和处理null值。首先,介绍了内部调用导致注解不生效的解决方案,随后讲解了如何配置缓存null值和在注解中添加条件避免缓存空结果。
摘要由CSDN通过智能技术生成

简介

Spring-boot 整合缓存服务之Redis 使用遇到的问题及解决方案。

简单集成可参考:1. Spring-boot 整合缓存服务之Redis简单集成

注解使用可参考:2. Spring-boot 整合缓存服务之Redis 注解方式使用

问题1:@Cacheable缓存不生效的

原因:Spring 缓存注解是基于AOP切面,必须走代理才能生效,同类调用或者子类调用父类带有缓存注解的方法时属于内部调用,没有走代理,所以注解不生效。

解决:将方法抽离到一个独立类中。

参考博客:spring boot 中缓存使用 @Cacheable redis缓存不生效

 

问题2:数据库中数据为null,但是限制缓存中不可存放null。 

 

原因:使用@Cacheable 或者 @CachePut 数据库中数据为null,但是限制缓存中不可存放null。

解决:1. 修改配置,修改可以缓存null值。

spring:
  cache:
    redis:
      cache-null-values: true #是否缓存空值

2. 使用的注解中加入限制(unless = "#result == null")返回值为null不进行数据缓存。 可参考:2. Spring-boot 整合缓存服务之Redis 注解方式使用 查看其余使用方法。

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbintel.mom.factory.dao.NumberCreateDao;
import com.zbintel.mom.factory.entity.NumberCreateEntity;
import com.zbintel.mom.factory.service.NumberCreateCacheService;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


@Service("numberCreateCacheService")
public class NumberCreateCacheServiceImpl extends ServiceImpl<NumberCreateDao, NumberCreateEntity>  implements NumberCreateCacheService {

    
    /**
     * 设置其 value : CREATE_NUMBER_RECORDING  (组的概念)
     *       key : infoDate:companyId:type  (获取请求参数中的对应值, : 号分割后给其进行组分割)
     *       unless : 排除result 为 null的情况
     * @param companyId
     * @param type
     * @param infoDate
     * @return
     */
    @Cacheable(value = "CREATE_NUMBER_RECORDING", key = "#infoDate+':'+#companyId+':'+#type",unless="#result == null")
    public NumberCreateEntity queryCache(String companyId,String type, String infoDate) {
        QueryWrapper<NumberCreateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(NumberCreateEntity::getType,type).eq(NumberCreateEntity::getInfoDate,infoDate)
                .eq(NumberCreateEntity::getCompanyId,companyId);
        return baseMapper.selectOne(queryWrapper);
    }
}

参考博客:SpringBoot在使用@Cacheable缓存对象为空时遇到的坑

 

参考博客

spring boot 中缓存使用 @Cacheable redis缓存不生效

SpringBoot在使用@Cacheable缓存对象为空时遇到的坑

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值