Java遠程方法調用(RMI,Remote Method Invocation)是一種用于在Java虛擬機(JVM)之間進行通信和對象調用的機制。它允許一個Java程序(客戶端)調用另一個Java程序(服務端)中的方法,就像調用本地方法一樣。要實現Java遠程方法調用,需要遵循以下步驟:
java.rmi.Remote
接口,并為每個要遠程調用的方法聲明throws java.rmi.RemoteException
異常。import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MyRemoteInterface extends Remote {
String sayHello(String name) throws RemoteException;
}
java.rmi.server.UnicastRemoteObject
類,并在構造函數中調用super()
方法,傳入遠程接口的實例。import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class MyRemoteInterfaceImpl extends UnicastRemoteObject implements MyRemoteInterface {
protected MyRemoteInterfaceImpl() throws RemoteException {
super();
}
@Override
public String sayHello(String name) throws RemoteException {
return "Hello, " + name + "!";
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
MyRemoteInterface remoteObject = new MyRemoteInterfaceImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("MyRemoteInterface", remoteObject);
System.out.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
MyRemoteInterface remoteObject = (MyRemoteInterface) registry.lookup("MyRemoteInterface");
String result = remoteObject.sayHello("World");
System.out.println("Client received: " + result);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
sayHello
方法,并輸出結果。注意:在實際應用中,還需要考慮安全性、異常處理和性能優化等問題。這里只是一個簡單的示例,用于演示Java遠程方法調用的基本概念。