DRYing up a generic RedisTemplate in Spring 4

我只是一个虾纸丫 提交于 2019-12-04 07:50:55

I had the same issue. You could create a generic bean for this, and use the GenricJackson2JsonRedisSerializer. The issue is that by using this the json will be saved with some extra data for the deserialization to work later on.

Another way would be to use the Jackson2JsonRedisSerializer but it needs the Class instance of the generic type to work, witch i couldnt figure out how to get.

@Bean("objectRedisTemplate")
public <T> RedisTemplate<String, T> objectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, T> redisTemplate = new RedisTemplate<>();

    redisTemplate.setConnectionFactory(redisConnectionFactory);

    RedisSerializer<String> serializer = new StringRedisSerializer();
    redisTemplate.setKeySerializer(serializer);
    redisTemplate.setHashKeySerializer(serializer);

    redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

    return redisTemplate;
}

Usage on cache class:

@Autowired
@Qualifier("objectRedisTemplate")
private RedisTemplate<String, MyTypeA> redisTemplate;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!