我看到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 的所有序列化对象,以减少盒子之间的网络流量。
谢谢
最佳答案
我最终通过以下方式解决了这个问题。
- 创建 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;
}
- 创建自定义序列化器。我决定扩展 JdkSerializationRedisSerializer,因为这是 Spring 默认为 Redis 使用的。我在每个受人尊敬的方法中添加了压缩/解压缩,并使用父类(super class)序列化代码。
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();
}
}
- 对
RedisTemplate
Bean 使用 spring 依赖注入(inject)。
关于spring - 使用 LettuceConnectionFactory 向 Spring Data Redis 添加压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58829724/