在分散式系統中,網路頻寬常成為效能瓶頸。特別是 RMI(Remote Method Invocation)應用,大量物件序列化傳輸時,資料量龐大。若能在傳輸前壓縮資料,再由客戶端解壓縮,可大幅降低網路負載。
ZipInputStream 與 ZipOutputStream 並不限於檔案操作,只需將資料轉為位元組陣列(byte[])即可串流式壓縮/解壓縮。
為讓 RMI 自動使用壓縮通道,需自訂 Socket 工廠並註冊給遠端物件:
public class ZipSocket extends Socket {
private InputStream in;
private OutputStream out;
public ZipSocket() { super(); }
public ZipSocket(String host, int port) throws IOException {
super(host, port);
}
@Override
public InputStream getInputStream() throws IOException {
if (in == null) {
in = new ZipInputStream(super.getInputStream());
}
return in;
}
@Override
public OutputStream getOutputStream() throws IOException {
if (out == null) {
out = new ZipOutputStream(super.getOutputStream());
}
return out;
}
@Override
public synchronized void close() throws IOException {
OutputStream o = getOutputStream();
o.flush();
super.close();
}
}
public class ZipServerSocket extends ServerSocket {
public ZipServerSocket(int port) throws IOException {
super(port);
}
@Override
public Socket accept() throws IOException {
Socket socket = new ZipSocket();
implAccept(socket);
return socket;
}
}
public class ZipClientSocketFactory implements RMIClientSocketFactory, Serializable {
@Override
public Socket createSocket(String host, int port) throws IOException {
return new ZipSocket(host, port);
}
}
public class ZipServerSocketFactory implements RMIServerSocketFactory, Serializable {
@Override
public ServerSocket createServerSocket(int port) throws IOException {
return new ZipServerSocket(port);
}
}
public class YourRemoteObject extends UnicastRemoteObject {
public YourRemoteObject(int port) throws RemoteException {
super(port, new ZipClientSocketFactory(), new ZipServerSocketFactory());
}
// 實作遠端介面方法...
}
RMIServerSocketFactory 建立伺服器端 ServerSocket,並透過 RMIClientSocketFactory 建立客戶端 Socket。ZipSocket 的 ZipOutputStream/ZipInputStream 透明壓縮/解壓縮。