首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java RMI 通訊資料壓縮:自訂 Socket Factory 實現透明 Zip 傳輸

     編輯:Java 相關知識

RMI 預設使用 Java 序列化傳輸物件,大物件頻繁傳輸佔用頻寬。透過實作 RMIClientSocketFactory / RMIServerSocketFactory 並繼承 UnicastRemoteObject,可在不修改業務介面的前提下,透明啟用 Zip 壓縮。

一、架構圖

Client Stub → ZipClientSocketFactory → ZipSocket (ZipOutputStream) → Network
Server Skeleton ← ZipServerSocketFactory ← ZipServerSocket ← ZipSocket (ZipInputStream)

二、核心類別實作

1. ZipSocket — 壓縮/解壓輸入輸出流

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();
    }
}

2. ZipServerSocket — 接受連線時回傳 ZipSocket

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;
    }
}

3. ZipClientSocketFactory

public class ZipClientSocketFactory implements RMIClientSocketFactory, Serializable {
    @Override public Socket createSocket(String host, int port) throws IOException {
        return new ZipSocket(host, port);
    }
}

4. ZipServerSocketFactory

public class ZipServerSocketFactory implements RMIServerSocketFactory, Serializable {
    @Override public ServerSocket createServerSocket(int port) throws IOException {
        return new ZipServerSocket(port);
    }
}

5. 遠端物件掛載 Factory

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);

四、效果與注意

  • 序列化資料經 Zip 壓縮,典型文字型物件壓縮率 70%~90%。
  • CPU 開銷微增,頻寬受限環境 (VPN、跨機房) 收益顯著。
  • 雙端必須部署相同 Factory 類,否則反序列化失敗。
  • 大二進位物件 (圖片、加密資料) 壓縮效果差,可考慮條件式啟用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved