在使用RedisTemplate存key的时候发现在redis的key是这样的:
在RedisTemplate源码里面可以知道默认序列化是使用的JdkSerializationRedisSerializer就是jdk自己的序列化方式
那就明了了,我们在创建的RedisTemplate指定序列化方式为阿里的FastJson2JsonRedisSerializer就可以了:
一开始没有指定:
需要引入阿里的fastjson pom依赖 ;新增FastJson2JsonRedisSerializer类,:
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
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(DEFAULT_CHARSET);
}
@Override
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);
}
}
添加序列化类
创建RedisTemplate的时候指定序列化:
@Bean
public RedisTemplate taskRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> configRedisTemplate = new RedisTemplate<>();
configRedisTemplate.setValueSerializer(fastJson2JsonRedisSerializer());
configRedisTemplate.setHashValueSerializer(fastJson2JsonRedisSerializer());
configRedisTemplate.setKeySerializer(new StringRedisSerializer());
configRedisTemplate.setHashKeySerializer(new StringRedisSerializer());
configRedisTemplate.setConnectionFactory(redisConnectionFactory);
return configRedisTemplate;
}
但是测试发现还是一样的:试了很多总都是不行,最后想了想还是直接使用StringRedisTemplate,不使用RedisTemplate
public StringRedisTemplate stringRedisTemplate() {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(rddConnectionFactory());
return template;
}
这样就好了…