我需要压缩/解压缩哈希表中包含的值。由于 LZ4 似乎提供比 GZip 更好的性能,我正在尝试。
这是我的代码。特别table_data_cache
是HashMap<String, List<Object>>
,每个列表有 2 个对象,只有第一个对象需要压缩
压缩
table_data_cache.forEach((kk,vv) -> {
try{
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(vv.get(0));
byte[] source = b.toByteArray();
int decompressedLength = source.length;
LZ4Factory factory = LZ4Factory.fastestInstance();
LZ4Compressor compressor = factory.fastCompressor();
int maxCompressedLength = compressor.maxCompressedLength(decompressedLength);
byte[] compressed = new byte[maxCompressedLength];
int compressLen = compressor.compress(source, 0, decompressedLength, compressed, 0, maxCompressedLength);
byte[] finalCompressedArray = Arrays.copyOf(compressed, compressLen);
List<Object> list = new ArrayList<>();
list.add(finalCompressedArray);
list.add(vv.get(1));
table_data_cache_compressed.put(kk, list);
}catch(Exception e){
e.printStackTrace();
}
减压
table_data_cache_compressed.forEach((kkk,vvv)->{
List<AbstractClass> list = new ArrayList<>();
try{
LZ4Factory factory = LZ4Factory.fastestInstance();
LZ4FastDecompressor decompressor = factory.fastDecompressor();
byte[] src = (byte[])vvv.get(0);
byte[] restored = "".getBytes();
decompressor.decompress(src, restored);
ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(restored));
list = (List<AbstractClass>) objectIn.readObject();
CacheStatus status = (CacheStatus) vvv.get(1);
System.out.println("key: "+kkk+" ID1: "+list.get(0).getParameterValue("REG_MAP_ID", "int", section_name)+" timestamp: "+status.getTIMESTAMP());
}
catch(Exception e){
e.printStackTrace();
}
CacheStatus status = (CacheStatus) vvv.get(1);
System.out.println("key: "+kkk+" ID1: "+list.get(0).getParameterValue("REG_MAP_ID", "int", section_name)+" timestamp: "+status.getTIMESTAMP());
});
但我有以下错误:
net.jpountz.lz4.LZ4Exception:错误解码输入缓冲区的偏移量 1
怎么了?