简介
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中使用Redis缓存时遇到的两个常见问题:@Cacheable注解失效和处理null值。首先,介绍了内部调用导致注解不生效的解决方案,随后讲解了如何配置缓存null值和在注解中添加条件避免缓存空结果。
1万+





