fastjson2 序列化 redistemplate
时间: 2025-06-18 11:39:58 浏览: 22
### 使用 FastJson2 配置 RedisTemplate 序列化
为了使 `RedisTemplate` 能够使用 FastJson2 进行序列化和反序列化,需要创建自定义的序列化类以及配置 `RedisTemplate` 来应用这些设置。
#### 自定义序列化器实现
通过继承 `Jackson2JsonRedisSerializer` 并重写其方法来适配 FastJson2 的需求。不过对于 FastJson2 更常见的做法是直接利用其实现序列化的特性构建新的序列化工具类:
```java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
static {
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
private Class<T> clazz;
public FastJson2JsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null){
return new byte[0];
}
try{
return JSON.toJSONBytes(t);
} catch(Exception e){
throw new SerializationException("Serialization failure", e);
}
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if(bytes==null || bytes.length<=0){
return null;
}
try{
return JSON.parseObject(bytes,clazz);
}catch(Exception e){
throw new SerializationException("Deserialization failure",e);
}
}
}
```
此段代码展示了如何基于 FastJson2 创建一个通用的对象序列化/反序列化工厂[^3]。
#### 配置 RedisTemplate 使用新序列化器
接下来,在 Spring Boot 中配置 `RedisTemplate` 以便它能识别上述定制好的序列化逻辑:
```java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 设置键(Key)的序列化采用 String 方式
template.setKeySerializer(new StringRedisSerializer());
// 设置值(Value)的序列化采用 FastJson2 方式
FastJson2JsonRedisSerializer<Object> fastJson2JsonRedisSerializer =
new FastJson2JsonRedisSerializer<>(Object.class);
template.setValueSerializer(fastJson2JsonRedisSerializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(fastJson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
```
这段配置指定了当存取对象时应使用的具体序列化机制,从而解决了默认情况下难以阅读的问题,并提高了开发效率[^2]。
阅读全文
相关推荐



















