使用 spring-data-redis 将原始 json 存储在 redis 中
我正在使用 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模板中显式设置jackson序列化器.
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;
}
相关文章