From 03d97ca4c2bb1cfaf025b8ca44fa7c51bbacd774 Mon Sep 17 00:00:00 2001 From: ZZ Date: Fri, 22 Apr 2022 09:57:06 +0800 Subject: [PATCH] zip it --- .../main/java/com/xhpc/common/Compressor.java | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 xhpc-modules/xhpc-common/src/main/java/com/xhpc/common/Compressor.java diff --git a/xhpc-modules/xhpc-common/src/main/java/com/xhpc/common/Compressor.java b/xhpc-modules/xhpc-common/src/main/java/com/xhpc/common/Compressor.java new file mode 100644 index 00000000..b8eb5cc5 --- /dev/null +++ b/xhpc-modules/xhpc-common/src/main/java/com/xhpc/common/Compressor.java @@ -0,0 +1,100 @@ +package com.xhpc.common; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Base64; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class Compressor { + + + /** + * 使用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 String(Base64.getEncoder().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 = Base64.getDecoder().decode(compressedStr); + in = new ByteArrayInputStream(compressed); + ginzip = new GZIPInputStream(in); + byte[] buffer = new byte[1024]; + int offset = -1; + while ((offset = ginzip.read(buffer)) != -1) { + out.write(buffer, 0, offset); + } + decompressed = out.toString(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (ginzip != null) { + try { + ginzip.close(); + } catch (IOException e) { + } + } + if (in != null) { + try { + in.close(); + } catch (IOException e) { + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + } + } + } + return decompressed; + } + + public static void main(String[] args) { + + String compress = compress("2020年9月8日 — 背景Redis缓存的字符串过大时会有问题。不超过10KB最好,最大不能超过1MB。有几个热点配置缓存,5分钟命中一次,大小在5KB到6MB" + + "不等,因此需要压缩。"); + System.out.println(compress); + System.out.println(compress.length()); + String uncompress = uncompress(compress); + System.out.println(uncompress); + System.out.println(uncompress.length()); + } + +}