Java rmi遠程方法調用基本用法解析
本文主要介紹Java中的rmi的基本使用
1:項目架構
api:主要是接口的定義,url地址,端口號
rmiconsumer:rmi服務的調用者
rmiserver:rmi服務的提供者
2:pom.xnl
api的pom.xml
<artifactId>api</artifactId><groupId>com.api</groupId><version>1.0</version> rmiconsumer和rmiserver的pom.xml<dependency><groupId>com.api</groupId><artifactId>api</artifactId><version>1.0</version></dependency>
該功能主要是將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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
