RMI 預設使用 Java 序列化傳輸物件,大物件頻繁傳輸佔用頻寬。透過實作 RMIClientSocketFactory / RMIServerSocketFactory 並繼承 UnicastRemoteObject,可在不修改業務介面的前提下,透明啟用 Zip 壓縮。
Client Stub → ZipClientSocketFactory → ZipSocket (ZipOutputStream) → Network
Server Skeleton ← ZipServerSocketFactory ← ZipServerSocket ← ZipSocket (ZipInputStream)
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 {
if (out != null) out.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());
}
// 業務方法...
}
// Server
Registry registry = LocateRegistry.createRegistry(1099);
YourRemoteObject obj = new YourRemoteObject(0); // 0 讓系統分配端口
registry.rebind("MyService", obj);