在SpringBoot中操作redis时,发现key多了\xac\xed\x00\x05t\x00\x02前缀
原因:
我们注入的RedisTemplate在对Redis进行操作时,采用了
JdkSerializationRedisSerializer对数据进行序列化
this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
@Nullable
private RedisSerializer<?> defaultSerializer;
@Nullable
private ClassLoader classLoader;
@Nullable
private RedisSerializer keySerializer = null;
@Nullable
private RedisSerializer valueSerializer = null;
@Nullable
private RedisSerializer hashKeySerializer = null;
@Nullable
private RedisSerializer hashValueSerializer = null;
如上代码所示,对我们的key进行了JdkSerializationRedisSerializer序列化操做,所以就导致了我们的key前面出现了\xac\xed\x00\x05t\x00\x02k1这些字符
解决办法:非常简单
将注入的RedisTemplate改为StringRedisTemplate注入即可完成
@Autowired
private StringRedisTemplate redisTemplate;
原理:StringRedisTemplate采用了RedisSerializer.string()方法,将二进制数据转换为字符串
public class StringRedisTemplate extends RedisTemplate<String, String> {
public StringRedisTemplate() {
this.setKeySerializer(RedisSerializer.string());
this.setValueSerializer(RedisSerializer.string());
this.setHashKeySerializer(RedisSerializer.string());
this.setHashValueSerializer(RedisSerializer.string());
}