redis的value过大解决方案

背景:

最近在工作中遇到一个业务场景:需要把近一年的不同类型的历史数据存储到缓存里。

但是当我在redis管理工具中打开这个key的时候,,redis manager desktop 居然崩溃了。。。

后来换了个软件,打开一看,缓存大小居然达到了2M,而查出来的JSON数据居然达到了11w行。。

大小2.25MB,大key无疑了

后来在网上找了一圈

解决方案:

先序列化,再使用gzip进行压缩,存入redis,取的时候先解压,然后反序列化,然后返回

最终效果:

同样的数据,压缩之后,体积缩小了大约八倍!!!

代码如下

使用gzip压缩工具类:

/**
     * 使用gzip压缩字符串
     *
     * @param originString 要压缩的字符串
     * @return 压缩后的字符串
     */
    public static String compress(String originString) {
        if (originString == null || originString.length() == 0) {
            return originString;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (
                GZIPOutputStream gzip = new GZIPOutputStream(out);
        ) {
            gzip.write(originString.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new sun.misc.BASE64Encoder().encode(out.toByteArray());
    }
 
    /**
     * 使用gzip解压缩
     *
     * @param compressedString 压缩字符串
     * @return
     */
    public static String uncompress(String compressedString) {
        if (compressedString == null || compressedString.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] compressedByte = new byte[0];
        try {
            compressedByte = new sun.misc.BASE64Decoder().decodeBuffer(compressedString);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String originString = null;
        try (
                ByteArrayInputStream in = new ByteArrayInputStream(compressedByte);
                GZIPInputStream ginzip = new GZIPInputStream(in);
        ) {
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            originString = out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return originString;

————————————————
 
原文链接:https://blog.csdn.net/u010398771/article/details/110431821

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值