Java中RMI遠程調用
Java遠程方法調用,即Java RMI(Java Remote Method Invocation)是Java編程語言里,一種用于實現遠程過程調用的應用程序編程接口。它使客戶機上運行的程序可以調用遠程服務器上的對象。遠程方法調用特性使Java編程人員能夠在網絡環境中分布操作。RMI全部的宗旨就是盡可能簡化遠程接口對象的使用。
Java RMI極大地依賴于接口。在需要創建一個遠程對象的時候,程序員通過傳遞一個接口來隱藏底層的實現細節。客戶端得到的遠程對象句柄正好與本地的根代碼連接,由后者負責透過網絡通信。這樣一來,程序員只需關心如何通過自己的接口句柄發送消息。
服務端新建接口:
import java.rmi.Remote; import java.rmi.RemoteException; public interface RmiTestInterface extends Remote{ public String getTest() throws RemoteException; } |
接口的實現:
import java.rmi.RemoteException; public class RmiTestImpl implements RmiTestInterface { public RmiTestImpl() throws RemoteException { //super(); // TODO Auto-generated constructor stub //UnicastRemoteObject.exportObject(this); } /** * */ public String getTest() throws RemoteException { // TODO Auto-generated method stub return "Hello,Test"; } } |
定義一個main方法,注冊你已經實現的RMI接口,包括開放端口等:
public static void main(String []args) throws AlreadyBoundException, RemoteException{ RmiTestImpl t=new RmiTestImpl(); RmiTestInterface tt=(RmiTestInterface)UnicastRemoteObject.exportObject(t,0); // Bind the remote object's stub in the registry Registry registry = LocateRegistry.createRegistry(2001); registry.rebind("test", tt); System.out.println("server is start"); } |
Server端的代碼已經全部寫完,但是還要把接口類(RmiTestInterface)打包成jar,導入進client端的項目中。
運行服務端后控制臺輸出:
server is start
導入服務端的接口jar以后,可以開始編寫一個client端的主程序:
public static void main(String []args){ try { Registry registry = LocateRegistry.getRegistry("localhost",2001); RmiTestInterface t= (RmiTestInterface) registry.lookup("test"); System.out.println("client:"+t.getTest()); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotBoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } |
運行客戶端main方法后,控制臺輸出:
Hello,Test