我最终通过以下方式解决了它。
- 创建一个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的方式。我在每个受关注的方法中都添加了压缩/解压缩,并使用了超类序列化代码。
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依赖注入。
,
这是Java Spring Boot Redis集群数据配置的示例。
这是Redis Cluster和Redis Cache Manager的实现。
- 快速压缩
- Kryo序列化
- 每个缓存键支持ttl
- 等级配置
- spring-data-redis
- snappy-java
- kryo
- 通用编解码器
Link to github https://github.com/cboursinos/java-spring-redis-compression-snappy-kryo
本文链接:https://www.f2er.com/3113079.html