springboot3 整合redis 使用fastjson
时间: 2025-06-21 07:03:13 浏览: 19
### 整合 Spring Boot 3 和 Redis 使用 FastJSON 进行序列化/反序列化
为了在基于 Spring Boot 3 的应用程序中整合 Redis 并使用 FastJSON 来处理对象的序列化和反序列化,可以遵循以下方法:
#### 添加依赖项
首先,在 `pom.xml` 文件中添加必要的 Maven 依赖来支持 Redis 和 FastJSON。
```xml
<dependencies>
<!-- Spring Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Fastjson2 for JSON processing -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.27</version>
</dependency>
<!-- Optional: If using Lettuce as the connection factory -->
<dependency>
<groupId>io.lettuce.core</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>
</dependencies>
```
#### 配置 RedisTemplate
接着定义一个自定义配置类用于设置 `RedisTemplate` 及其序列化策略。这里采用 FastJSON 作为默认序列化工具体现。
```java
import com.alibaba.fastjson2.JSON;
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.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// Key 序列化方式; String 类型 -> StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
// Value 序列化方式;Object 转 json -> GenericJackson2JsonRedisSerializer 或者 自定义实现
template.setValueSerializer((value) -> {
if(value instanceof String || value == null){
return value;
}
return JSON.toJSONString(value);
});
// Hash key 序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
// Hash value 序列化方式
template.setHashValueSerializer((value) -> {
if(value instanceof String || value == null){
return value;
}
return JSON.toJSONString(value);
});
template.afterPropertiesSet();
return template;
}
}
```
此部分展示了如何通过编程的方式创建了一个带有特定序列化逻辑的 `RedisTemplate` 实例[^1]。
#### 编写服务层代码
最后编写业务逻辑中的数据存取操作,利用上述模板来进行缓存读写的例子如下所示:
```java
@Service
@Slf4j
public class CacheService {
private final RedisTemplate<String,Object> redisTemplate;
@Autowired
public CacheService(@Qualifier("redisTemplate") RedisTemplate<String,Object> redisTemplate){
this.redisTemplate=redisTemplate;
}
/**
* 存储单个key-value到Redis.
*/
public void setCacheData(String key, Object data){
try{
log.info("Put into cache with key :{},data:{}",key,data.toString());
redisTemplate.opsForValue().set(key,data);
}catch(Exception e){
throw new RuntimeException(e.getMessage(),e.getCause());
}
}
/**
* 获取指定键对应的值.
*/
public Object getCacheData(String key){
try{
Object result = redisTemplate.opsForValue().get(key);
log.info("Get from cache with key:{},result:{}",key,result==null?"":result.toString());
return result;
}catch(Exception e){
throw new RuntimeException(e.getMessage(),e.getCause());
}
}
}
```
这段程序片段说明了怎样运用之前设定好的 `RedisTemplate` 对象执行基本的数据存储与检索命令.
阅读全文
相关推荐




















