redis 序列化配置 string object自动转换
- 序列化异常导致 需要增加一个配置类
- 所谓序列化就是将对象转换为字节流的过程,以便传输或存储,并在需要时通过反序列重新构建对象.
- redis不能直接存Java对象. 自带的api不能直接保存. 为了方便开发需要自定义一个 redisTemplate1
- 注入的时候使用autowired + Quolifier
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
@Configuration public class RedisConfig {
@Bean @SuppressWarnings("all") public RedisTemplate<String, Object> redisTemplate1(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); 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();
template.setKeySerializer(stringRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet();
return template; }
}
|
测试依旧报错. 后发现在注入时使用Qualifier指定类名后解决.
1 2 3 4 5
| @Autowired @Qualifier("redisTemplate1") public RedisTemplate redisTemplate;
|