当我们使用RedisTemplate向我们的Redis数据库中set(“originName”)时,我们在服务端中获取该key的时候出现了乱码\
xac\xed\x00\x05t\x00\noriginName`
原因:因为我们springboot中的RedisTemplate将我们的key保存的时候会将其进行序列化,此时我们在别的客户端获取的时候机会出现乱码。
解决:我们需要自己定义我们的RedisTemplate中的序列化机制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Configuration public class RedisTemplateConfig { @Bean public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory){ RedisTemplate<Object, Object> objectObjectRedisTemplate = new RedisTemplate<>(); objectObjectRedisTemplate.setKeySerializer(new StringRedisSerializer()); objectObjectRedisTemplate.setHashKeySerializer(new StringRedisSerializer()); objectObjectRedisTemplate.setConnectionFactory(connectionFactory); return objectObjectRedisTemplate; } } |
由于我们获取值时会将它进行反序列化,我们就无须设置value的反序列化
from:https://blog.csdn.net/ebdbbd/article/details/126266968
另一个版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory , GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer , StringRedisSerializer stringRedisSerializer) { RedisTemplate objectObjectRedisTemplate = new RedisTemplate(); objectObjectRedisTemplate.setConnectionFactory(redisConnectionFactory); objectObjectRedisTemplate.setKeySerializer(stringRedisSerializer); objectObjectRedisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer); objectObjectRedisTemplate.setHashKeySerializer(stringRedisSerializer); objectObjectRedisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer); return objectObjectRedisTemplate; } |