jtn*_*ire 2 java compression rmi hashmap
我们有一个通过RMI进行通信的客户端/服务器应用程序.服务器将HashMaps发送到客户端.一切正常,但是当发送大型HashMaps时,传输时间可能很慢.
有没有办法在发送之前压缩HashMaps,然后在客户端上解压缩?我不想在磁盘上创建任何文件(所有文件必须在RAM中)
谢谢
您可以将DeflatorOutputStream用于ByteArrayOutputStream,但最终会得到一个byte [],因此您的RMI调用应该返回一个byte [].
小的可序列化的obejct不能很好地压缩,但是如果你有很多Serializable对象,它可以很好地压缩.所以可以有大量的文字.
最简单的方法是尝试它.如果有重复的字符串甚至是字符串的一部分,这将有助于压缩.
public static void main(String... args) throws IOException {
Map<String, String> map = new HashMap<String, String>();
for(int i=0;i<1000;i++)
map.put(""+Math.random(), ""+Math.random());
byte[] bytes1 = toBytes(map);
byte[] bytes2 = toCompressedBytes(map);
System.out.println("HashMap with "+map.size()+" entries, Uncompressed length="+bytes1.length+", compressed length="+bytes2.length);
}
public static byte[] toCompressedBytes(Object o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new DeflaterOutputStream(baos));
oos.writeObject(o);
oos.close();
return baos.toByteArray();
}
public static byte[] toBytes(Object o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return baos.toByteArray();
}
public static Object fromCompressedBytes(byte[] bytes) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new InflaterInputStream(new ByteArrayInputStream(bytes)));
return ois.readObject();
}
Run Code Online (Sandbox Code Playgroud)
打印
HashMap with 1000 entries, Uncompressed length=42596, compressed length=19479
Run Code Online (Sandbox Code Playgroud)