分布式系列五: RMI通信

 

RPC(Remote Procedure Call)协议

RPC协议是一种通过网络从远程计算机上请求服务, 而不需要了解底层网络技术的协议, 在OSI模型中处在应用层和网络层.

作为一个规范, 使用RPC协议的框架有很多, Dubbo,Hessian等均使用这个协议, RMI也使用该协议实现.

RMI(Remote Method Invocation) 远程方法调用

RMI使用Java远程消息交换协议JRMP(Java Remote Messaging Protocol)进行通信,JRMP是纯java的.

  1. 定义接口, 使其extends Remote接口, 方法需要抛出异常RemoteException, Remote是一个标记接口
public interface IRmiTest extends Remote {     String hello() throws RemoteException; }
  1. 实现接口, 使其extends UnicastRemoteObject, 需要有构造方法, 并抛出异常RemoteException
public class RmiTest extends UnicastRemoteObject implements IRmiTest {      public RmiTest() throws RemoteException {      }      @Override     public String hello() {         return "Hello ....";     } }
  1. 定义服务端, 注册和绑定
public class TestServer {     public static void main(String[] args) throws RemoteException, AlreadyBoundException, MalformedURLException {         IRmiTest rmiTest = new RmiTest();         LocateRegistry.createRegistry(8888);         Naming.bind("rmi://localhost:8888/hello",rmiTest);         System.out.println("server started");     } }
  1. 定义客户端, lookup方法的参数url与服务端bind的必须一致. 接口需要定义为与服务端一致.
public class TestClient {     public static void main(String[] args) throws RemoteException,  MalformedURLException, NotBoundException {         IRmiTest rmiTest = (IRmiTest) Naming.lookup("rmi://localhost:8888/hello");         System.out.println(rmiTest.hello());     } }

RMI实现机制

RMI屏蔽了底层复杂的网络调用, 使得远程对象的方法调用变得透明, 就像调用本地方法一样方便.
下面深入探究下jdk中rmi的实现原理, 看看底层是如何实现远程调用的.
首先, 需要了解下比较重要的两个角色stub和skeleton, 这两个角色封装了与网络相关的代码. 原始的交互式这样的,客户端--网络--服务器--具体服务. 有了这两个角色之后的模型变为: 客户端--stub--网络--skeleton--服务器--服务.可以参考的图

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信