在使用spring-data-redis,默认情况下是使用org.springframework.data.redis.serializer.JdkSerializationRedisSerializer这个类来做序列化,Jackson redis序列化是spring中自带的.我们使用jackson方式
@Bean(name="redisTemplate")
public RedisTemplate redisTemplate() {
Jackson2JsonRedisSerializer
使用fastjson方式:
public class FastJson2JsonRedisSerializer implements RedisSerializer {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class clazz;
public FastJson2JsonRedisSerializer(Class clazz) {
super();
this.clazz = clazz;
}
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T) JSON.parseObject(str, clazz);
}
}
注册
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactory factory;
@Autowired
private RedisSerializer fastJson2JsonRedisSerializer;
//fastjson
@Bean(name="redisTemplate")
public RedisTemplate fastJsonRedisTemplate() {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
//redis开启事务
template.setEnableTransactionSupport(true);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(fastJson2JsonRedisSerializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(fastJson2JsonRedisSerializer);
template.setDefaultSerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
在redis工具类中调用RedisTemplate:
@Component
public class RedisCacheUtil {
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate redisTemplate;
}
对比:
jackson方式序列化存储redis中数据:
[
"com.qhong.test.dependBean.Person",
{
"age": 20,
"name": "name0",
"iss": true
}
]
[
"java.util.ArrayList",
[
[
"com.qhong.test.dependBean.Person",
{
"age": 20,
"name": "name0",
"iss": true
}
],
[
"com.qhong.test.dependBean.Person",
{
"age": 21,
"name": "name1",
"iss": true
}
],
[
"com.qhong.test.dependBean.Person",
{
"age": 22,
"name": "name2",
"iss": true
}
]
]
]
上面的完全不符合json格式规范
fastjson方式序列化:
{
"@type": "com.qhong.test.dependBean.Person",
"age": 20,
"iss": true,
"name": "name0"
}
[
{
"@type": "com.qhong.test.dependBean.Person",
"age": 20,
"iss": true,
"name": "name0"
},
{
"@type": "com.qhong.test.dependBean.Person",
"age": 21,
"iss": true,
"name": "name1"
},
{
"@type": "com.qhong.test.dependBean.Person",
"age": 22,
"iss": true,
"name": "name2"
}
]
虽然也不是很好,但是比jackson的好多了