I am using Spring Redis support to save my objects in Redis.
I have several DAOs which handle different Model classes :
eg : 'ShopperHistoryDao' which will save/retrieve objects of 'ShopperHistoryModel' 'ShopperItemHistoryDao' which will handle objects of 'ItemHistoryModel'
I want to use 'JacksonJsonRedisSerializer' to serialise/deserialize my objects to/from json.
But in the constructor of JacksonJsonRedisSerializer, it takes one specific Model class.
JacksonJsonRedisSerializer(Class<T> type)
Does that mean, I have to configure separate RedisTemplates for each different Model class and use them in appropriate DAO implementation?
Something like :
<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>
Yes, the
RedisTemplate
seems to be designed to have a single instance of the value serializer.I was going to suggest the possible workaround of having a
RedisSerializer
which contains a Map of inner serializers so you can use oneRedisTemplate
with a serializer that can handle multiple types - but sinceRedisSerializer
does not offer methods likeboolean canDeserialize(..)
(as the HTTP MessageConverters in Spring MVC have) this doesn't seem possible.So it seems that you are stuck with having multiple
RedisTemplate
instances.A bit of old thread, but you can do something like this:
Then in your Java class
GenericJackson2JsonRedisSerializer should do the job
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.
In the service you can cache the model using
Check this article: http://blog.pranavek.com/2016/12/25/integrating-redis-with-spring-application