您好,登錄后才能下訂單哦!
Java遠(yuǎn)程方法調(diào)用(RMI)允許在一個(gè)Java虛擬機(jī)(JVM)上的對(duì)象調(diào)用另一個(gè)JVM上的子類方法
java.rmi.Remote
接口,并為每個(gè)要遠(yuǎn)程調(diào)用的方法聲明拋出java.rmi.RemoteException
異常。import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteInterface extends Remote {
String sayHello() throws RemoteException;
}
RemoteException
異常。import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class RemoteImplementation extends UnicastRemoteObject implements RemoteInterface {
public RemoteImplementation() throws RemoteException {
super();
}
@Override
public String sayHello() throws RemoteException {
return "Hello from remote implementation!";
}
}
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try {
RemoteInterface remoteObject = new RemoteImplementation();
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("RemoteInterface", 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);
RemoteInterface remoteObject = (RemoteInterface) registry.lookup("RemoteInterface");
String result = remoteObject.sayHello();
System.out.println("Result from server: " + result);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
在這個(gè)例子中,客戶端通過RMI注冊(cè)表查找名為"RemoteInterface"的遠(yuǎn)程對(duì)象,并調(diào)用其sayHello()
方法。遠(yuǎn)程對(duì)象在服務(wù)器上實(shí)現(xiàn),并通過RMI注冊(cè)表暴露給客戶端。這樣,客戶端就可以像調(diào)用本地對(duì)象一樣調(diào)用遠(yuǎn)程對(duì)象的方法,實(shí)現(xiàn)了跨JVM的遠(yuǎn)程方法調(diào)用。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。