Java rmi远程方法调用基本用法解析
陌然浅笑 人气:2本文主要介绍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> <https://img.qb5200.com/download-x/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
加载全部内容