本文主要介紹Java中的rmi的基本使用
1:項目架構
api:主要是接口的定義,url地址,端口號
rmiconsumer:rmi服務的調用者
rmiserver:rmi服務的提供者
2:pom.xnl
api的pom.xml
api com.api 1.0 rmiconsumer和rmiserver的pom.xml com.api api 1.0
該功能主要是將api的引入到服務端和客戶端
3:代碼
api的代碼
public interface RMIInterface extends Remote { String RMI_URL = "rmi://127.0.0.1:9080/RMIServer"; int PORT = 9080; Object sayHello(String name) throws RemoteException; }
rmiserver的代碼
public class RMIInterfaceImpl extends UnicastRemoteObject implements RMIInterface { public RMIInterfaceImpl() throws RemoteException { } @Override public Object sayHello(String name) throws RemoteException { return "你好,你連接成功,姓名:"+name; } }
public class RMIServer { public static void main(String[] args) { try { RMIInterface rmi = new RMIInterfaceImpl(); //註冊通訊端口 LocateRegistry.createRegistry(RMIInterface.PORT); //註冊通訊路徑 Naming.bind(RMIInterface.RMI_URL,rmi); System.out.println("rmi服務端啟動成功"); }catch (Exception e){ e.printStackTrace(); } } }
rmiconsumer
public class RMIConsumer { public static void main(String[] args) { //遠程調用RMI RMIInterface rmiInterface =null; try{ rmiInterface =(RMIInterface) Naming.lookup(RMIInterface.RMI_URL); Object ret = rmiInterface.sayHello("張先生"); System.out.println("測試遠程調用成功,返回結果:"+ret); }catch (Exception e){ e.printStackTrace(); } } }
4:總結
接口必須繼承 Remote
接口的實現類必須繼承 UnicastRemoteObject
[madbeef ] Java rmi遠程方法調用基本用法解析已經有234次圍觀