복붙노트

[SPRING] Spring RedisTemplate : 여러 모델 클래스를 JSON으로 serialize합니다. 여러 RedisTemplates를 사용해야합니까?

SPRING

Spring RedisTemplate : 여러 모델 클래스를 JSON으로 serialize합니다. 여러 RedisTemplates를 사용해야합니까?

Redis에서 내 개체를 저장하기 위해 Spring Redis 지원을 사용하고 있습니다.

다른 모델 클래스를 처리하는 여러 DAO가 있습니다.

예 : 'ShopperHistoryDao'는 'ShopperHistoryModel'의 객체를 저장 / 검색합니다. 'ShopperItemHistoryDao'는 'ItemHistoryModel'의 객체를 처리합니다.

json에서 /로 객체를 serialize / deserialize하기 위해 'JacksonJsonRedisSerializer'를 사용하고 싶습니다.

그러나 JacksonJsonRedisSerializer의 생성자에서는 하나의 특정 Model 클래스를 사용합니다.

JacksonJsonRedisSerializer(Class<T> type)

즉, 각각의 다른 Model 클래스에 대해 별도의 RedisTemplates를 구성하고 적절한 DAO 구현에 사용해야합니다.

같은 것 :

<bean id="redisTemplateForShopperHistoryModel" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="jedisConnectionFactory" />
    <property name="valueSerializer">
        <bean id="redisJsonSerializer" 
                        class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer">
            <constructor-arg type="java.lang.Class" value="ShopperHistoryModel.class"/>
        </bean>   
    </property>
</bean>


<bean id="redisTemplateForItemHistoryModel" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="jedisConnectionFactory" />
    <property name="valueSerializer">
        <bean id="redisJsonSerializer" 
                        class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer">
            <constructor-arg type="java.lang.Class" value="ItemHistoryModel.class"/>
        </bean>   
    </property>
</bean>

해결법

  1. ==============================

    1.GenericJackson2JsonRedisSerializer가 작업을 수행해야합니다.

    GenericJackson2JsonRedisSerializer가 작업을 수행해야합니다.

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

    이렇게하면 JSON에 @Class 속성이 추가되어 유형을 이해할 수 있으므로 Jackson이 직렬화를 해제하는 데 도움이되므로 모델을 구성 클래스에 명시 적으로 매핑 할 필요가 없습니다.

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

    이 서비스에서 다음을 사용하여 모델을 캐시 할 수 있습니다.

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

    이 기사 확인 : http://blog.pranavek.com/2016/12/25/integrating-redis-with-spring-application

  2. ==============================

    2.예, RedisTemplate은 값 직렬 변환기의 단일 인스턴스를 갖도록 설계된 것 같습니다.

    예, RedisTemplate은 값 직렬 변환기의 단일 인스턴스를 갖도록 설계된 것 같습니다.

    나는 여러 가지 유형을 처리 할 수있는 serializer로 하나의 RedisTemplate을 사용할 수 있도록 내부 serializer의 Map을 포함하는 RedisSerializer를 사용할 수있는 해결 방법을 제안하려고했지만 RedisSerializer는 boolean canDeserialize (..)와 같은 메소드를 제공하지 않기 때문에 (as Spring MVC의 HTTP MessageConverters)이 가능하지는 않습니다.

    그래서 당신은 여러 개의 RedisTemplate 인스턴스를 가지고있는 것으로 보입니다.

  3. ==============================

    3.오래된 스레드의 비트,하지만 당신은 이런 식으로 할 수 있습니다 :

    오래된 스레드의 비트,하지만 당신은 이런 식으로 할 수 있습니다 :

    <bean id="RedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
        <property name="valueSerializer">
            <bean id="jackson2JsonRedisSerializer" 
                            class="org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer">
                <constructor-arg type="java.lang.Class" value="Object.class" />
            </bean>   
        </property>
    </bean>
    

    그런 다음 Java 클래스에서

    @Autowire
    private RedisTemplate redisTemplate;
    
    public void save(Model model) {
        ObjectMapper obmap = new ObjectMapper();
        redisTemplate.opsForHash().putAll(mode.getId(), obmap.convertValue(model, Map.class));
    }
    
  4. from https://stackoverflow.com/questions/21672245/spring-redistemplate-serialise-multiple-model-classes-into-json-need-to-use-mu by cc-by-sa and MIT license