来自rocketmq源码,rocketmq中消息默认超过4KB,会进行压缩
evel为压缩层级,rocketmq源码中默认level为5
-
压缩
public static byte[] compress(final byte[] src, final int level) throws IOException { byte[] result = src; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length); java.util.zip.Deflater defeater = new java.util.zip.Deflater(level); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, defeater); try { deflaterOutputStream.write(src); deflaterOutputStream.finish(); deflaterOutputStream.close(); result = byteArrayOutputStream.toByteArray(); } catch (IOException e) { defeater.end(); throw e; } finally { try { byteArrayOutputStream.close(); } catch (IOException ignored) { } defeater.end(); } return result; }
-
解压缩
public static byte[] uncompress(final byte[] src) throws IOException {
byte[] result = src;
byte[] uncompressData = new byte[src.length];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(src);
InflaterInputStream inflaterInputStream = new InflaterInputStream(byteArrayInputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
try {
while (true) {
int len = inflaterInputStream.read(uncompressData, 0, uncompressData.length);
if (len <= 0) {
break;
}
byteArrayOutputStream.write(uncompressData, 0, len);
}
byteArrayOutputStream.flush();
result = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
throw e;
} finally {
try {
byteArrayInputStream.close();
} catch (IOException e) {
log.error("Failed to close the stream", e);
}
try {
inflaterInputStream.close();
} catch (IOException e) {
log.error("Failed to close the stream", e);
}
try {
byteArrayOutputStream.close();
} catch (IOException e) {
log.error("Failed to close the stream", e);
}
}
return result;
}