1.起因
在本地搭建了一个项目用来测试SpringBoot利用SpringCache整合Redis哨兵模式,写了如下配置类:
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用Jackson2JsonRedisSerialize 替换默认的jdkSerializeable序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(new StringRedisSerializer(StandardCharsets.UTF_8));
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
然后在可视化工具中,看到的却是乱码:
2.解决办法
上网查了一下,如果整合了SpringCache的话,还需要修改CacheManager的序列化方式,在配置类中新增如下代码
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// 根据 Redis 连接工厂构建 Redis 缓存管理器
return RedisCacheManager.builder(redisConnectionFactory)
// 默认的缓存配置
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
// 序列化key
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))
// 序列化value
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json())))
// 启用 Redis 缓存,使缓存放置/驱逐操作与正在进行的 Spring 管理的事务同步。
.transactionAware()
// 构建
.build();
}
我们再放入一条数据查看
搞定~