压缩Redis里的字符串大对象

本文探讨了当Redis中字符串大对象导致性能问题时,如何使用gzip和Zstd进行压缩。建议字符串大小不超过10KB,但实际大小在5KB到6MB之间,因此提出两种压缩方案以优化缓存效率。
摘要由CSDN通过智能技术生成

背景

  • Redis缓存的字符串过大时会有问题。不超过10KB最好,最大不能超过1MB。
  • 有几个配置缓存,上千个flink任务调用,每个任务5分钟命中一次,大小在5KB到6MB不等,因此需要压缩。

第一种,使用gzip

/**
 * 使用gzip压缩字符串
 */
public static String compress(String str) {
   
    if (str == null || str.length() == 0) {
   
        return str;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = null;
    try {
   
        gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
    } catch (IOException e) {
   
        e.printStackTrace();
    } finally {
   
        if (gzip != null) {
   
            try {
   
                gzip.close();
            } catch (IOException e) {
   
                e.printStackTrace();
            }
        }
    }
    return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
 
/**
 * 使用gzip解压缩
 */
public static String uncompress(String compressedStr) {
   
    if (compressedStr == null || compressedStr.length() == 0) {
   
        return compressedStr;
    }
 
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = null;
    GZIPInputStream ginzip = null;
    byte[] compressed = null;
    String decompressed = null;
    try {
   
        compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
        in = new
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值