问题描述
我使用 Spring Redis 支持将我的对象保存在 Redis 中.
I am using Spring Redis support to save my objects in Redis.
我有几个处理不同模型类的 DAO:
I have several DAOs which handle different Model classes:
例如,ShopperHistoryDao
保存/检索ShopperHistoryModel
的对象,ShopperItemHistoryDao
保存/检索ItemHistoryModel
的对象.
For example, ShopperHistoryDao
save/retrieve objects of ShopperHistoryModel
, ShopperItemHistoryDao
save/retrieve objects of ItemHistoryModel
.
我想使用 JacksonJsonRedisSerializer
将我的对象序列化/反序列化到 json 中.
I want to use JacksonJsonRedisSerializer
to serialise/deserialize my objects to/from json.
但是在 JacksonJsonRedisSerializer 的构造函数中,它需要一个特定的 Model 类.
But in the constructor of JacksonJsonRedisSerializer, it takes one specific Model class.
JacksonJsonRedisSerializer(Class<T> type)
这是否意味着,我必须为每个不同的 Model 类配置单独的 RedisTemplates
并在适当的 DAO 实现中使用它们?
Does that mean, I have to configure separate RedisTemplates
for each different Model class and use them in appropriate DAO implementation?
类似于:
<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>
推荐答案
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 反序列化,因此无需在配置类上显式映射模型.
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"}"
在服务中,您可以使用
@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
这篇关于Spring RedisTemplate:将多个模型类序列化为 JSON.需要使用多个 RedisTemplates?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!