问题描述
我正在使用RedisCacheManager将缓存数据存储在我的spring-boot应用程序中.默认的序列化程序似乎将所有内容序列化为字节,然后从字节反序列化为适当的Java类型.
I am using RedisCacheManager to store my cache data in my spring-boot application. Default serializer seems to serialize everything into byte and deserialize from byte to appropriate java type.
但是,我想将缓存数据存储为json,以便可以从非Java客户端读取它.
However, I want to make the cache data be stored as json so that I can read it from none-java clients.
我发现从默认的序列化器切换到其他的序列化器(如Jackson2JsonRedisSerializer)应该可以正常工作.完成此操作后,反序列化阶段将失败.
I found that switching from default one to other serializers such as Jackson2JsonRedisSerializer supposed to work. After doing this, deserialization phase fails.
pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
CacheConfig.java
CacheConfig.java
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisConnectionFactory createRedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName("localhost");
return factory;
}
// SPRING-DATA-REDIS ALREADY PROVIDES A STRING REDIS TEMPLATE, SO THE FOLLOWING IS NOT NECESSARY
// @Bean
// public RedisTemplate<String, String> createRedisTemplate(RedisConnectionFactory factory) {
// RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
// redisTemplate.setConnectionFactory(factory);
// return redisTemplate;
// }
@Bean
public CacheManager redisCacheManager(RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
return cacheManager;
}
}
有没有一种方法可以将它们存储为纯JSON格式并从中成功反序列化?
Is there a way to store them in a pure JSON format and successfully deserialize from it?
推荐答案
将此添加到您的配置中以在redis模板中显式设置杰克逊序列化器.
add this in your configuration to explicitly set the jackson serializer in redis template.
public @Bean RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
这篇关于通过使用spring-data-redis将原始json存储在Redis中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!