java 使用 spring-data-redis 在 redis 中存储原始 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41875635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:12:46  来源:igfitidea点击:

storing raw json in redis by using spring-data-redis

javajsonspringserializationspring-data

提问by Muatik

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.

我正在使用 RedisCacheManager 将我的缓存数据存储在我的 spring-boot 应用程序中。默认序列化程序似乎将所有内容序列化为字节并将字节反序列化为适当的 java 类型。

However, I want to make the cache data be stored as json so that I can read it from none-java clients.

但是,我想让缓存数据存储为 json,以便我可以从非 Java 客户端读取它。

I found that switching from default one to other serializers such as Hymanson2JsonRedisSerializer supposed to work. After doing this, deserialization phase fails.

我发现从默认序列化器切换到其他序列化器(例如 Hymanson2JsonRedisSerializer)应该可以工作。执行此操作后,反序列化阶段失败。

pom.xml

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

缓存配置文件

@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;
    }
}

Is there a way to store them in a pure JSON format and successfully deserialize from it?

有没有办法以纯 JSON 格式存储它们并成功反序列化?

回答by Monzurul Haque Shimul

add this in your configuration to explicitly set the Hymanson serializer in redis template.

将此添加到您的配置中以在 redis 模板中显式设置 Hymanson 序列化程序。

public @Bean RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {

    RedisTemplate<Object, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setDefaultSerializer(new GenericHymanson2JsonRedisSerializer());
    template.setKeySerializer(new StringRedisSerializer());
    template.setHashKeySerializer(new GenericHymanson2JsonRedisSerializer());
    template.setValueSerializer(new GenericHymanson2JsonRedisSerializer());
    return template;
}

回答by nimai

As of spring-data-jpa:2.0.2.RELEASE at least, configuring the default redis template does not affect how the @Cacheable annotation family accesses redis. Anyway, since I'm using a redis template for more than that, it's not something I want to do.

至少从 spring-data-jpa:2.0.2.RELEASE 开始,配置默认的 redis 模板不会影响 @Cacheable 注解族访问 redis 的方式。无论如何,由于我使用的 redis 模板不止于此,这不是我想做的事情。

This, however, isolates the configuration for the cache manager and works as expected:

但是,这会隔离缓存管理器的配置并按预期工作:

@Configuration
@EnableCaching
public class RedisCacheManagerConfiguration {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public CacheManager redisCacheManager() {
        RedisSerializationContext.SerializationPair<Object> jsonSerializer = 
         RedisSerializationContext.SerializationPair.fromSerializer(new GenericHymanson2JsonRedisSerializer());
         return RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(redisConnectionFactory)
                .cacheDefaults(
                    RedisCacheConfiguration.defaultCacheConfig()
                            .entryTtl(Duration.ofDays(1))
                            .serializeValuesWith(jsonSerializer)
                )
                .build();
    }

}

It makes use of the generic Json serializer for Redis (GenericHymanson2JsonRedisSerializer).

它使用 Redis 的通用 Json 序列化器 (GenericHymanson2JsonRedisSerializer)。

You can also configure other aspects of the cache manager, such as the time-to-live of the key in redis.

您还可以配置缓存管理器的其他方面,例如密钥在 redis 中的生存时间。

回答by mgalala

I managed to make this by defining RedisConnectionFactory

我设法通过定义 RedisConnectionFactory 来做到这一点

@Bean
public RedisConnectionFactory jedisPool()
{
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(new JedisPoolConfig());
    jedisConnectionFactory.setHostName("localhost");

    return jedisConnectionFactory;
}

and then using StringRedisTemplate

然后使用 StringRedisTemplate

ValueOperations<String, String> ops = redisTemplate.opsForValue();
ops.set("key", "Json_string");

I hope this might help!

我希望这可能会有所帮助!