RMI简单学习
简单的说一下rmi的原理
接口,必须要有实现接口
package rmi; import java.rmi.Remote; import java.rmi.RemoteException; public interface IHello extends Remote { public String sayHello(String name) throws RemoteException; }
首先是服务端,服务端的流程就是,
- 服务端创建远程对象:服务端定义一个远程接口和实现类,实现类继承自
UnicastRemoteObject
并实现远程接口的方法。 - 服务端注册远程对象:服务端使用
LocateRegistry.createRegistry()
启动 RMI 注册表,然后使用Naming.rebind()
将远程对象绑定到注册表中
package rmi; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.UnicastRemoteObject; public class RMIServer { public class RMIHello extends UnicastRemoteObject implements IHello{ protected RMIHello() throws RemoteException{ super(); } @Override public String sayHello(String name) throws RemoteException{ System.out.println("Hello,World"); return name; } } private void register() throws Exception{ RMIHello rmiHello = new RMIHello(); LocateRegistry.createRegistry(1099); Naming.bind("rmi://0.0.0.0:1099/hello",rmiHello); System.out.println("Registry运行中......"); } public static void main(String[] args) throws Exception{ new RMIServer().register(); } }
客户端的流程就是
- 客户端查找远程对象:客户端使用
Naming.lookup()
查找远程对象,并通过它来调用远程方法。 - 处理远程异常:在远程方法调用中可能会抛出
RemoteException
,所以无论是在服务端还是客户端都需要处理这些异常。package rmi; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class RMIClient { public static void main(String[] args) throws Exception{ Registry registry = LocateRegistry.getRegistry("127.0.0.1", 1099); IHello iHello = (IHello) registry.lookup("hello"); System.out.println(iHello.sayHello("Feng")); } } 整体原理就是:服务端通过启动注册表,绑定远程对象,然后在使客户端查找这个对象,来调用远程方法