I am using redis as my caching store in my application. For that i am using the following redis configuration:
@Configuration
@EnableCaching
public class SpringRedisConfig {
@Bean
public JedisConnectionFactory connectionFactory() {
JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
connectionFactory.setHostName("localhost");
connectionFactory.setPort(6379);
return connectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
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);
//template.setConnectionFactory(factory);
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
return redisTemplate;
}
}
and in my services to store data in cache, i am using @Cacheable as follows:
@Cacheable(value = "institute_detail_cache", key = "'inst_'+#instituteId")
public Map<String, String> getDetailsFromCache(Long instituteId) {
log.info("not found in cache.....");
Map<String, String> map = new HashMap<>();
map.put("name", "kayv");
map.put("age", "20");
return map;
}
The code is working fine and storing the data in cache as object. Here is the value as i got from redis cli:
But my requirement is to store the data(value) as json, with key-value pairs. That is why i have used Jackson2JsonRedisSerializer for the value serialisation.
Can anyone suggest what wrong i am doing?
And what should i need to implement to make my classes to be store as json instead of map as i used in this example?