赞
踩
远程过程调用(Remote Procedure Call,RPC)是一个计算机通信协议。该协议允许运行于一台计算机的程序调用另一台计算机的子程序,同时将网络的通信细节隐藏起来,而程序员无需额外的为这个交互作用编程。RPC采用客户机/服务器模型。
请求过程如图:
客户端程序->客户端Stub程序 ->通信模块 -> 远程请求 -> 通信模块 -> 调度程序 -> 服务器端Stub程序 -> 服务程序
**
**
package org.example.RpcTest; import org.apache.hadoop.ipc.VersionedProtocol; import java.io.IOException; public interface MethodProtocol extends VersionedProtocol { public static final long versionID=1L; int calculate(int v1,int v2) throws IOException; } package org.example.RpcTest; import org.apache.hadoop.ipc.ProtocolSignature; import java.io.IOException; public class MethodProtocolImpl implements MethodProtocol { public long getProtocolVersion(String protocol,long clientVersion){ return MethodProtocol.versionID; } public ProtocolSignature getProtocolSignature(String protocol, long clientVersion, int hashcode){ return new ProtocolSignature(MethodProtocol.versionID,null); } @Override public int calculate(int v1, int v2) throws IOException { return ((v1+v2)/2); } } package org.example.RpcTest; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Arrays; public class RpcClient { public static void main(String[] args) throws IOException { MethodProtocol proxy; InetSocketAddress addr = new InetSocketAddress("localhost",8866); Configuration conf = new Configuration(); proxy = (MethodProtocol) RPC.getProxy(MethodProtocol.class,MethodProtocol.versionID,addr,conf); int result = proxy.calculate(7,7); System.out.println(result); } } package org.example.RpcTest; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.Server; import java.io.IOException; import java.util.Arrays; public class RpcServer { public static void main(String[] args) { Configuration conf = new Configuration(); Server server = null; try { server = new RPC.Builder(conf).setProtocol(MethodProtocol.class).setInstance(new MethodProtocolImpl()).setBindAddress("localhost") .setPort(8866).setNumHandlers(5).build(); } catch (IOException e) { e.printStackTrace(); } server.start(); System.out.println("server begin ....."); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。