Spring RedisTemplate : Serialise multiple Model classes into JSON.Need to use Multiple RedisTemplates?

后端 未结 3 1246
野性不改
野性不改 2020-12-29 05:38

I am using Spring Redis support to save my objects in Redis.

I have several DAOs which handle different Model classes:

For example, ShopperHistoryDao

3条回答
  •  半阙折子戏
    2020-12-29 05:49

    GenericJackson2JsonRedisSerializer should do the job

        @Bean
        public RedisTemplate redisTemplate() {
            RedisTemplate redisTemplate = new RedisTemplate();
            redisTemplate.setConnectionFactory(jedisConnectionFactory());
            redisTemplate.setKeySerializer(new StringRedisSerializer());                                           
            redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
            return redisTemplate;
        }
    

    This will add @Class property to the JSON to understand the type, which helps Jackson to deserialize, so no need to explicitly map the model on the configuration class.

    "{\"@class\":\"com.prnv.model.WhitePaper\",\"title\":\"Hey\",\"author\":{\"@class\":\"com.prnv.model.Author\",\"name\":\"Hello\"},\"description\":\"Description\"}"
    

    In the service you can cache the model using

        @Cacheable(value = "whitePaper", key = "#title")
        public WhitePaper findWhitePaperByTitle(String title) 
        {
            WhitePaper whitePaper = repository.findByTitle(title);
            return whitePaper;
        }
    

    Check this article: http://blog.pranavek.com/2016/12/25/integrating-redis-with-spring-application

提交回复
热议问题