Java RMI(Remote Method Invocation,遠程方法調用) 是 Java 原生提供的分布式計算機制,允許運行在一個 JVM 中的對象調用另一個 JVM(可能在不同機器)中對象的方法。它是 EJB、分布式框架的基石,雖然歷史悠久(JDK 1.1 即引入),但在內部系統、高性能 RPC 場景仍具優勢。
RMI 開發遵循標準四步驟:
java.rmi.Remote,方法拋出 RemoteException。UnicastRemoteObject,實現業務邏輯。LocateRegistry.createRegistry() 和 Naming.bind()。Naming.lookup() 獲取存根調用方法。import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IHello extends Remote {
String helloWorld() throws RemoteException;
String sayHelloToSomeBody(String someBodyName) throws RemoteException;
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloImpl extends UnicastRemoteObject implements IHello {
public HelloImpl() throws RemoteException { super(); }
@Override
public String helloWorld() throws RemoteException {
return "Hello World!";
}
@Override
public String sayHelloToSomeBody(String someBodyName) throws RemoteException {
return "你好," + someBodyName + "!";
}
}
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class HelloServer {
public static void main(String[] args) {
try {
IHello rhello = new HelloImpl();
// 創建註冊表,指定端口 8888(默認 1099)
LocateRegistry.createRegistry(8888);
// 綁定對象,URL 格式:rmi://host:port/name
Naming.bind("rmi://localhost:8888/RHello", rhello);
System.out.println(">>> INFO: 遠程 IHello 對象綁定成功!");
} catch (RemoteException | AlreadyBoundException | MalformedURLException e) {
e.printStackTrace();
}
}
}
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class HelloClient {
public static void main(String[] args) {
try {
IHello rhello = (IHello) Naming.lookup("rmi://localhost:8888/RHello");
System.out.println(rhello.helloWorld());
System.out.println(rhello.sayHelloToSomeBody("熔巖"));
} catch (NotBoundException | MalformedURLException | RemoteException e) {
e.printStackTrace();
}
}
}
啟動服務端後,再運行客戶端,控制台將輸出:
Hello World!
你好,熔巖!
RMI 是理解分布式調用原理的絕佳切入點。雖然生產環境多採用 Dubbo、gRPC、Spring Cloud 等現代框架,但 RMI 的存根/骨架模型、註冊發現機制、序列化傳輸等核心思想始終貫穿其中。掌握 RMI,有助於深入理解 RPC 框架底層原理。