使用LettuceConnectionFactory向Spring数据Redis添加压缩
我看到莴苣可以对Redis序列化对象进行压缩: 有没有办法在Spring引导数据LettuceConnectionFactory或其他bean中设置此配置?我在这里也看到了这样一个问题: 我想压缩发送到Redis的所有序列化对象,以减少盒子之间的网络流量使用LettuceConnectionFactory向Spring数据Redis添加压缩,spring,redis,compression,gzip,lettuce,Spring,Redis,Compression,Gzip,Lettuce,我看到莴苣可以对Redis序列化对象进行压缩: 有没有办法在Spring引导数据LettuceConnectionFactory或其他bean中设置此配置?我在这里也看到了这样一个问题: 我想压缩发送到Redis的所有序列化对象,以减少盒子之间的网络流量 谢谢我最后用下面的方法解决了这个问题 创建一个springbean模板。这允许我们设置自定义序列化程序 对RedisTemplateBean使用spring依赖注入 下面是一个JavaSpringBootRedis集群数据配置的示例 它是一个带
谢谢我最后用下面的方法解决了这个问题
RedisTemplate
Bean使用spring依赖注入李>
下面是一个JavaSpringBootRedis集群数据配置的示例 它是一个带有Redis集群和Redis缓存管理器的实现
使用
IOUtils.copy(new GZIPInputStream(new ByteArrayInputStream(contentBytes)),out)是否有特定的原因代码>而不是只执行GZIPOutputStream GZIPOutputStream=new GZIPOutputStream(out);gzipOutputStream.write(contentBytes)代码>无具体原因。我想我只是在谷歌上搜索了如何处理gzip数据,并使用了我发现的第一个堆栈溢出。
@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;
}
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();
}
}