在使用RedisTemplate,redisTemplate.opsForHash(),set值的时候可以正常set,但是在使用redisTemplate.opsForHash().entries报错序列化出错:
很明显原因是:序列化冲突了。
RedisTemplate默认的序列化方式是:org.springframework.data.redis.serializer.JdkSerializationRedisSerializer,而Redis本身是有自己的序列化方式,所以两种序列化方式冲突了。
解决方案
加上如下的配置类:
@Configuration
public class RedisClusterConfiguration {
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionfactory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
redisTemplate.setConnectionFactory(redisConnectionfactory);
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}