使用hadoop RPC实现RPC调用

来源:互联网 发布:网络签约作者收入 编辑:程序博客网 时间:2024/04/26 11:54

环境:

hadoop1.1.2


一、 定义服务提供的对象的接口, 此接口必须extends org.apache.hadoop.ipc.VersionedProtocol

eg.

import org.apache.hadoop.ipc.VersionedProtocol;/** * 业务接口, must extends VersionedProtocol * @author Administrator * */public interface MyBiz extends VersionedProtocol{// 业务方法public abstract String hello(String name);}

二、定义服务提供的对象的接口实现类

eg.

import java.io.IOException;/** * 业务接口实现类 * @author Administrator * */public class MyBizImpl implements MyBiz {static long VERSION = 123L;@Overridepublic String hello(String name) {System.out.println("invoked here!");return "hello " + name;}@Overridepublic long getProtocolVersion(String protocol, long clientVersion)throws IOException {return VERSION;}}

三、 定义RPC Server端运行类

eg.

/** * RPC Server端 * @author Administrator * */public class MyServer {// Server hostnamestatic final String BIND_ADDRESS = "localhost";// Server portstatic final int BIND_PORT = 12345;public static void main(String[] args) throws Exception {// 在指定的hostname和port提供业务接口实现对象服务Server server = RPC.getServer( new MyBizImpl(), BIND_ADDRESS, BIND_PORT, new Configuration());// 启动服务server.start();}}

四、 定义RPC Client端运行类

eg.

/** * RPC Client端 * @author Administrator * */public class MyClient {public static void main(String[] args) throws Exception {// 在指定的hostname和port获取服务提供的业务接口代理对象MyBiz proxy = (MyBiz)RPC.waitForProxy(MyBiz.class, MyBizImpl.VERSION, new InetSocketAddress(MyServer.BIND_ADDRESS, MyServer.BIND_PORT), new Configuration());// 调用代理对象的业务方法String v = proxy.hello("calvin");System.out.println(v);// 关闭代理对象RPC.stopProxy(proxy);}}

五、说明

1. 服务端提供的对象的定义和执行在server端, 调用在client端


2. 服务端提供的对象必须是一个接口,并且extends VersioinedProtocal

0 0
原创粉丝点击