解决方案
消息压缩
压缩解压代码如下:
@Slf4j
public class StringCompressUtils {
/**
* 使用gzip压缩字符串
*
* @param str 要压缩的字符串
* @return 压缩结果字符
*/
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) {
log.error("字符串压缩异常!", e);
e.printStackTrace();
} finally {
IoUtil.close(gzip);
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
/**
* 使用gzip解压缩
*
* @param compressedStr 压缩字符串
* @return 解压缩字符串
*/
public static String uncompress(String compressedStr) {
if (compressedStr == null) {
return null;
}
byte[] compressed = null;
String decompressed = null;
GZIPInputStream ginzip = null;
ByteArrayInputStream in = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// 先解码
compressed = new sun.misc.BASE64Decoder().decodeBuffer(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) {
log.error("字符串解压缩异常!", e);
e.printStackTrace();
} finally {
// 关流
IoUtil.close(ginzip);
IoUtil.close(in);
IoUtil.close(out);
}
return decompressed;
}
压缩流程:原始字符 -> 压缩 -> 压缩字符 -> 编码
解压流程:压缩字符 -> 解码 -> 解压 -> 原始字符