【Spring Boot 3 + fastjson2】更改RedisTemplate的序列化策略
在Spring Boot 3中,若要使用fastjson2作为RedisTemplate的序列化策略,你需要自定义配置类来覆盖默认的配置。以下是一个示例代码:
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.serializer.SerializerFeature;
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.RedisSerializer;
import java.nio.charset.StandardCharsets;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 使用fastjson序列化
FastJson2JsonRedisSerializer fastJson2JsonRedisSerializer = new FastJson2JsonRedisSerializer(Object.class);
// 设置值(value)的序列化器
template.setValueSerializer(fastJson2JsonRedisSerializer);
// 设置键(key)的序列化器
template.setKeySerializer(fastJson2JsonRedisSerializer);
// 设置哈希键的序列化器
template.setHashKeySerializer(fastJson2JsonRedisSerializer);
// 设置哈希值的序列化器
template.setHashValueSerializer(fastJson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
public static class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
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];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, StandardCharsets.UTF_8);
return JSON.parseObject(str, clazz);
}
}
}
在这个配置类中,我们定义了一个RedisTemplate
的Bean,并且使用了自定义的FastJson2JsonRedisSerializer
作为序列化器。这个序列化器使用fastjson2库将对象序列化为JSON字符串,并在反序列化时指
评论已关闭