Springboot2.X自定义RedisCache,统一处理value=NULL情况

本文介绍了在Springboot从1.x升级到2.x后,RedisCache的集成方式变化,特别是针对value为NULL的情况。由于RedisCache新增了allowNullValues属性,当value为NULL时,若设置为false会抛出异常。为避免每个注解都添加unless条件,作者选择重写RedisCacheManager的put方法,当value为NULL时不再抛异常,提供了一种统一的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近将Springboot从1.x升级到了2.x,发现redis的集成方式发生了比较大的变化。

还有就是RedisCache新增了属性allowNullValues:是否允许存储null对象。

当value=null时,如果allowNullValues=true时表示可以存储value对象;如果allowNullValues=false,就会抛出业务异常,除非在注解中增加unless="#result == null"

@Cacheable(key="'id'",unless="#result == null")

这样的问题是每个注解都需要增加unless。重写Rediscache的put方法,当value=null时不再抛出异常直接返回。

自定义RedisCacheManager

package com.redis.test;

import java.util.Map;

import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.spring
### Spring Boot 中使用 Redis 的配置与示例 #### 1. 引入依赖 为了在 Spring Boot 应用程序中集成 Redis,需要在项目的 `pom.xml` 文件中引入必要的依赖项。以下是所需的 Maven 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> ``` 这些依赖分别用于支持 Redis 数据访问以及缓存功能[^4]。 --- #### 2. 配置文件设置 在 `application.properties` 或 `application.yml` 文件中完成 Redis 连接的相关配置。以下是一个典型的配置示例: ##### application.properties 示例: ```properties # Redis 基本配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.database=0 # Redis Sentinel 配置(可选) spring.redis.sentinel.master=my-master spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 spring.redis.password=your-password ``` 如果项目未使用 Sentinel,则仅需提供基本的主机地址、端口和其他必要参数即可[^2]。 --- #### 3. 编写 Redis 配置类 可以通过自定义配置来调整 Redis 的行为,例如修改序列化方式或连接池参数。下面展示了一个简单的 Redis 配置类实现: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; @Configuration public class RedisConfig { @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { return new StringRedisTemplate(redisConnectionFactory); } } ``` 通过上述方法可以创建一个基于字符串键值对操作的模板工具实例[^3]。 --- #### 4. 使用 RedisTemplate 操作数据 借助于 `RedisTemplate` 提供的功能接口,可以直接执行各种 CRUD 操作。例如存储和获取简单键值对的操作如下所示: ```java @Autowired private StringRedisTemplate redisTemplate; // 存储数据到 Redis redisTemplate.opsForValue().set("myKey", "myValue"); // 从 Redis 获取数据 String value = redisTemplate.opsForValue().get("myKey"); System.out.println(value); // 输出 myValue ``` 此代码片段展示了如何利用 `opsForValue()` 方法处理普通的字符串类型的键值对。 --- #### 5. 启用并简化缓存操作 为了让应用程序能够更高效地管理缓存逻辑,可以在主启动类上添加 `@EnableCaching` 注解以激活 Spring Cache 功能。之后只需按照约定的方式标注目标方法即可自动触发对应的缓存读取/写入动作。 ```java @SpringBootApplication @EnableCaching public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @Service public class MyService { @Cacheable(value = "items", key = "#id") public Item findById(Long id) { System.out.println("Fetching from database..."); return itemRepository.findById(id).orElse(null); } @CachePut(value = "items", key = "#item.id") public Item update(Item item) { return itemRepository.save(item); } @CacheEvict(value = "items", key = "#id") public void deleteById(Long id) { itemRepository.deleteById(id); } } ``` 以上例子说明了怎样结合注解机制快速构建起一套完整的缓存解决方案。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值