1.背景
spring boot中使用redis,默认使用JdkSerializationRedisSerializer来序列化,但是默认的序列化会有个问题:java端存完了,取redis-cli执行:key * ,会发现键值都带有\xAC\xED\x00\x05t\x00\x05这种字符,这如果在集群环境下会导致问题!
2.实践
测试
@Testpublic void testSerializer(){
String stringRedisTemplateName = stringRedisTemplate.getKeySerializer().getClass().getName();System.out.println("stringRedisTemplateName = " + stringRedisTemplateName);String redisTemplateName = redisTemplate.getKeySerializer().getClass().getName();System.out.println("redisTemplateName = " + redisTemplateName);}
结果
stringRedisTemplateName = org.springframework.data.redis.serializer.StringRedisSerializer
redisTemplateName = org.springframework.data.redis.serializer.JdkSerializationRedisSerializer
可以看出默认stringRedisTemplate是StringRedisSerializer,而redisTemplate是JdkSerializationRedisSerializer;
redis-cli中
@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisSerializer stringSerializer = new StringRedisSerializer(); //指定SerializerRedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);template.setKeySerializer(stringSerializer);template.setValueSerializer(stringSerializer);return template;}
3.结论
redisTemplate使用默认的JdkSerializationRedisSerializer不利于集群以及与客户端的统一,可指定简单高效的StringRedisSerializer;
最后,如果看完对你有所帮助,不要吝啬关注 / 点赞 / 收藏哟,感谢感谢~