Hadoop RPC 四步法
(1) 定义协议 (2) 实现协议 (3) 定义服务端 (4) 定义客户端(1) 定义协议
public interface MethodProtocol extends VersionedProtocol{ public static final long versionID=1L; int calculate(int v1,int v2) throws IOException; }(2) 实现协议
public class MethodProtocolImpl implements MethodProtocol { public int calculate(int v1, int v2) throws IOException { return v1+v2; } public long getProtocolVersion(String protocol, long clientVersion) throws IOException { return MethodProtocol.versionID; } public ProtocolSignature getProtocolSignature(String protocol, long clientVersion, int clientMethodsHash) throws IOException { return new ProtocolSignature(MethodProtocol.versionID,null); } }(3) 实现服务端
public class MethodRpcServer { public static void main(String[] args) throws Exception{ Configuration conf = new Configuration(); RPC.Builder builder =new RPC.Builder(conf); builder.setBindAddress("localhost") .setPort(8888).setProtocol(MethodProtocol.class) .setInstance(new MethodProtocolImpl()); RPC.Server server=builder.build(); server.start(); } }(4) 实现客户端
public class MethodRpcClient { public static void main(String[] args) throws Exception{ MethodProtocol proxy = RPC.getProxy(MethodProtocol.class,MethodProtocol.versionID, new InetSocketAddress("localhost",8888),new Configuration()); int result = proxy.calculate(1,2); System.out.println(result); } }