redis — 如何将redis内存使用量压缩一半(四)

1.背景说明

redis存储有固定内存,如果以某种方式达到其内存极限,我们的系统将开始出现故障,Redis内存使用量可能会成为瓶颈。

使用最新版本的Spring Boot,有两个主要依赖项- Spring Boot Web和Spring Data Reactive Redis,Spring Data Reactive Redis将用于连接和使用Redis的内部应用程序。从本质上讲,Redis依赖项默认使用Lettuce Redis客户端,并且受最新版本的Spring Boot支持。

2.MessagePack

降低内存使用量使用MessagePack,MessagePack工作原理可以参照官网说明MsgPack spec.md,其特征以官方msgpack官网用一句话总结:It’s like JSON.but fast and small

引入依赖,在pom.xml文件中添加以下依赖项:

<!--redis内存压缩-->
<dependency>
    <groupId>org.msgpack</groupId>
    <artifactId>msgpack-core</artifactId>
    <version>0.8.20</version>
</dependency>
<dependency>
    <groupId>org.msgpack</groupId>
    <artifactId>jackson-dataformat-msgpack</artifactId>
    <version>0.8.20</version>
</dependency>

创建了一个名为控制器MsgPackController:

class MsgPackRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DEFAULT_CHARSET;
    private final JavaType javaType;
    private ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory())
            .registerModules(new Jdk8Module(), new JavaTimeModule())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
            .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL);

    public MsgPackRedisSerializer(Class<T> type) {
        this.javaType = JavaTypeHandler.getJavaType(type);
    }

    public T deserialize(@Nullable byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        } else {
            try {
                return this.objectMapper.readValue(bytes, 0, bytes.length, this.javaType);
            } catch (Exception ex) {
                throw new SerializationException("Could not read MsgPack JSON: " + ex.getMessage(), ex);
            }
        }
    }

    public byte[] serialize(@Nullable Object value) throws SerializationException {
        if (value == null) {
            return new byte[0];
        } else {
            try {
                return this.objectMapper.writeValueAsBytes(value);
            } catch (Exception ex) {
                throw new SerializationException("Could not write MsgPack JSON: " + ex.getMessage(), ex);
            }
        }
    }

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
    }

}

实例MessagePackFactory被传递到中ObjectMapper。这将充当Redis和我们的Spring Boot应用程序之间数据的二进制格式和字符串格式之间的桥梁。

3.压缩

比较dataset.bytes当前内存与先前记录的内存,使用率将减少一半,我们可以进一步减少它。

  • Snappy压缩算法

它不旨在最大程度地压缩,也不旨在与任何其他压缩库兼容。相反,它的目标是非常高的速度和合理的压缩。

使用Snappy就像在中添加依赖项一样简单pom.xml,并且几行代码更改。只需Snappy.compress在序列化和Snappy.decompress反序列化时添加即可:

<dependency>
    <groupId>org.xerial.snappy</groupId>
    <artifactId>snappy-java</artifactId>
    <version>1.1.7.3</version>
</dependency>

配置redis序列化配置类:

public class SnappyMsgPackRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DEFAULT_CHARSET;
    private final JavaType javaType;
    private ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory())
            .registerModules(new Jdk8Module(), new JavaTimeModule())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true)
            .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL);

    public SnappyMsgPackRedisSerializer(Class<T> type) {
        this.javaType = JavaTypeHandler.getJavaType(type);
    }

    @Override
    public T deserialize(@Nullable byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        } else {
            try {
                final byte[] uncompressBytes = Snappy.uncompress(bytes); //解压
                return this.objectMapper.readValue(uncompressBytes, 0, uncompressBytes.length, this.javaType);
            } catch (Exception ex) {
                throw new SerializationException("Could not read MsgPack JSON: " + ex.getMessage(), ex);
            }
        }
    }

    @Override
    public byte[] serialize(@Nullable Object value) throws SerializationException {
        if (value == null) {
            return new byte[0];
        } else {
            try {
                final byte[] bytes = this.objectMapper.writeValueAsBytes(value);
                return Snappy.compress(bytes); //压缩
            } catch (Exception ex) {
                throw new SerializationException("Could not write MsgPack JSON: " + ex.getMessage(), ex);
            }
        }
    }

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
    }
}

你可能感兴趣的:(redis,springboot,java,java,redis,缓存)