RPC(Remote Procedure Call)—远程过程调用协议,它是一种经过网络从远程计算机程序上请求服务,而不须要了解底层网络技术的协议。RPC协议假定某些传输协议的存在,如TCP或UDP,为通讯程序之间携带信息数据。在OSI网络通讯模型中,RPC跨越了传输层和应用层。RPC使得开发包括网络分布式多程序在内的应用程序更加容易。java
RPC采用客户机/服务器模式。请求程序就是一个客户机,而服务提供程序就是一个服务器。首先,客户机调用进程发送一个有进程参数的调用信息到服务进程,而后等待应答信息。在服务器端,进程保持睡眠状态直到调用信息的到达为止。当一个调用信息到达,服务器得到进程参数,计算结果,发送答复信息,而后等待下一个调用信息,最后,客户端调用进程接收答复信息,得到进程结果,而后调用执行继续进行。apache
Hadoop的整个体系结构就是构建在RPC之上的(见org.apache.hadoop.ipc包)服务器
使用RPC: (搭建一个Hadoop伪分布式虚拟机(Server端), 本地Windows链接该虚拟机(Client端))网络
1. 定义RPC协议接口 LoginProtocol (Hadoop RPC协议一般是一个Java接口), RPC协议接口是Client和Server之间的通讯接口, 它定义了Server对外提供的接口. LoginProtocol接口声明了一个login()方法, 须要注意的是Hadoop中全部自定义的RPC协议接口都有一个为versionID的字段, 它描述了该协议的版本信息, 这个RPC协议接口为Client/Server共同持有, Server端, Client端都必须有同一个LoginProtocol.class文件分布式
public interface LoginProtocol { public static final long versionID = 1L; public String login(String username, String password); }
2. 在Server端, LoginProtocolImpl 实现RPC协议接口( LoginProtocol )ide
public class LoginProtocolImpl implements LoginProtocol { @Override public String login(String username, String password) { return "wellcome " + username; } }
3. 在Server端构造并启动RPC Server, "192.168.8.101"是Server的ip地址, Server端监听了"1234"端口oop
public static void main(String[] args) throws HadoopIllegalArgumentException, IOException { // 设置4个必需参数: // setBindAddress("192.168.8.101") : Server端的IP地址 // setPort(1234) : 端口 // setProtocol(LoginProtocol.class) : setRPC协议接口的class对象 // setInstance(new LoginProtocolImpl()) : RPC协议接口的实现类的实例 Server server = new RPC.Builder(new Configuration()).setBindAddress("192.168.8.101").setPort(1234) .setProtocol(LoginProtocol.class).setInstance(new LoginProtocolImpl()).build(); server.start(); } }
4. 在Client端构造RPC客户端, 使用RPC类静态方法getProxy()构造客户端RPC代理对象( proxy ), 调用RPC代理对象( proxy )的login()方法, 发送RPC请求. "192.168.8.101"是Server的ip地址, "1234"是Server端监听端口ui
public class LoginClient { public static void main(String[] args) throws IOException { // getProxy()参数: // LoginProtocol.class : RPC协议接口的class对象 // 1L : RPC协议接口的版本信息(versionID) // new InetSocketAddress("192.168.8.101", 1234) : Server端的IP地址及端口 // conf : Configuration实例 LoginProtocol proxy = RPC.getProxy(LoginProtocol.class, 1L, new InetSocketAddress("192.168.8.101", 1234), new Configuration()); String result = proxy.login("rpc", "xxx"); System.out.println(result); } }
接下来, 神奇的一幕发生了!spa
本地Windows的Console输出:代理
wellcome rpc
本地Windows有LoginProtocol接口的实现吗?
没有哟!
至此, 利用Hadoop RPC搭建了一个简单的Client/Server分布式网络模型, 之后还会深刻Hadoop RPC内部