RMI(Java Remote Method Invocation)與 CORBA(Common Object Request Broker Architecture)是最重要、最廣泛使用的兩種分散式物件系統。本文簡介兩者架構,並以「從遠端主機下載檔案」為例,完整示範 RMI 開發流程,最後對比優劣。
傳統 C/S 需自行設計協議;分散式物件以明確封裝介面隔離客戶端與服務實作,客戶端發送訊息給物件,由物件或代理執行服務。RMI 與 CORBA 均屬此模型。
Remote,方法拋 RemoteException)UnicastRemoteObject)// 1. 遠端介面
public interface FileInterface extends Remote {
byte[] downloadFile(String fileName) throws RemoteException;
}
// 2. 實作
public class FileImpl extends UnicastRemoteObject implements FileInterface {
public byte[] downloadFile(String fileName) {
// 讀取檔案至 byte[] 回傳
}
}
// 3. 伺服器
Naming.rebind("//127.0.0.1/FileServer", new FileImpl("FileServer"));
// 4. 客戶端
FileInterface fi = (FileInterface) Naming.lookup("//host/FileServer");
byte[] data = fi.downloadFile("test.txt");
rmic FileImpl // 生成 Stub/Skeleton
rmiregistry [port] // 啟動 Registry
java -Djava.security.policy=policy.txt FileServer // 啟動伺服器
java FileClient fileName host // 啟動客戶端
| 維度 | RMI | CORBA |
|---|---|---|
| 語言綁定 | 純 Java | 多語言(IDL) |
| 程式模型 | 簡單,類似本地呼叫 | 複雜,學習曲線陡 |
| 可攜遷性 | 標準化契約佳 | 廠商實作不一,較差 |
| 服務整合 | 宣告式(安全/交易) | 需複雜 API |
| 網路協議 | JRMP / RMI-IIOP | IIOP |
RMI 以 Java 原生優勢、簡單模型、宣告式服務,成為 Java 分散式開發首選;CORBA 適合異構語言整合場景。