使用LettuceConnectionFactory向Spring Data Redis添加压缩

我看到Lettuce可以对Redis序列化对象进行压缩:https://lettuce.io/core/release/reference/#codecs.compression

在Spring Boot Data LettuceConnectionFactory或其他bean中设置此配置的任何方法吗?我也看到了这个问题:https://github.com/lettuce-io/lettuce-core/issues/633

我想压缩所有发送到Redis的序列化对象,以减少盒子之间的网络流量。

谢谢

smalltiger67 回答:使用LettuceConnectionFactory向Spring Data Redis添加压缩

我最终通过以下方式解决了它。

  1. 创建一个RedisTemplate Spring Bean。这使我们可以设置自定义序列化程序。
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<Object,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // Set a custom serializer that will compress/decompress data to/from redis
        RedisSerializerGzip serializerGzip = new RedisSerializerGzip();
        template.setValueSerializer(serializerGzip);
        template.setHashValueSerializer(serializerGzip);
        return template;
    }
  1. 创建自定义序列化程序。我决定扩展JdkSerializationRedisSerializer,因为这是Spring默认用于Redis的方式。我在每个受关注的方法中都添加了压缩/解压缩,并使用了超类序列化代码。
public class RedisSerializerGzip extends JdkSerializationRedisSerializer {

    @Override
    public Object deserialize(byte[] bytes) {
        return super.deserialize(decompress(bytes));
    }

    @Override
    public byte[] serialize(Object object) {
        return compress(super.serialize(object));
    }


    ////////////////////////
    // Helpers
    ////////////////////////
    private byte[] compress(byte[] content) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
            gzipOutputStream.write(content);
        } catch (IOException e) {
            throw new SerializationException("Unable to compress data",e);
        }
        return byteArrayOutputStream.toByteArray();
    }

    private byte[] decompress(byte[] contentBytes) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            IOUtils.copy(new GZIPInputStream(new ByteArrayInputStream(contentBytes)),out);
        } catch (IOException e) {
            throw new SerializationException("Unable to decompress data",e);
        }
        return out.toByteArray();
    }

}
  1. RedisTemplate Bean使用spring依赖注入。
,

这是Java Spring Boot Redis集群数据配置的示例。

这是Redis Cluster和Redis Cache Manager的实现。

  1. 快速压缩
  2. Kryo序列化
  3. 每个缓存键支持ttl
  4. 等级配置
  5. spring-data-redis
  6. snappy-java
  7. kryo
  8. 通用编解码器

Link to github https://github.com/cboursinos/java-spring-redis-compression-snappy-kryo

本文链接:https://www.f2er.com/3113079.html

大家都在问