今天发现使用redis序列化查询数据报错,于是debug调一下源码,我们可以看到这个redisTemplate的key的序列化和value的序列化类。
lALPGpb_8DLFM73NAmvNAng_632_619.png lALPGpNycY35SfTNAkrNAjA_560_586.png所以通过redisConfig可以对redisTemplate的序列化方法进行修改。
/**
*redis相关配置
*/
@Configuration
//开启注解缓存
@EnableCaching
publicclassRedisConfig{
/**
*redis序列化配置
*@paramconnectionFactoryjedis连接工厂
*@return
*/
@Bean
publicRedisTemplateredisTemplate(JedisConnectionFactoryconnectionFactory){
RedisTemplateredisTemplate=newRedisTemplate();
redisTemplate.setConnectionFactory(connectionFactory);
//使用Jackson2JsonRedisSerialize替换默认序列化
Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class);
ObjectMapperobjectMapper=newObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//设置value的序列化规则和key的序列化规则
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(newStringRedisSerializer());
redisTemplate.setHashKeySerializer(redisTemplate.getKeySerializer());
redisTemplate.afterPropertiesSet();
returnredisTemplate;
}
}
网友评论