RPC(Remote Procedure Call)协议
RPC协议是一种通过网络从远程计算机上请求服务, 而不需要了解底层网络技术的协议, 在OSI模型中处在应用层和网络层.
作为一个规范, 使用RPC协议的框架有很多, Dubbo,Hessian等均使用这个协议, RMI也使用该协议实现.
RMI(Remote Method Invocation) 远程方法调用
RMI使用Java远程消息交换协议JRMP(Java Remote Messaging Protocol)进行通信,JRMP是纯java的.
- 定义接口, 使其extends
Remote接口, 方法需要抛出异常RemoteException, Remote是一个标记接口
public interface IRmiTest extends Remote { String hello() throws RemoteException; }- 实现接口, 使其extends
UnicastRemoteObject, 需要有构造方法, 并抛出异常RemoteException
public class RmiTest extends UnicastRemoteObject implements IRmiTest { public RmiTest() throws RemoteException { } @Override public String hello() { return "Hello ...."; } }- 定义服务端, 注册和绑定
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"); } }- 定义客户端, 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--服务器--服务.可以参考的图
