您的位置:首页 > 运维架构

使用hadoop RPC实现RPC调用

2015-04-18 21:41 537 查看
环境:

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;

@Override
public String hello(String name) {
System.out.println("invoked here!");

return "hello " + name;
}

@Override
public long getProtocolVersion(String protocol, long clientVersion)
throws IOException {

return VERSION;
}

}


三、 定义RPC Server端运行类

eg.

/**
* RPC Server端
* @author Administrator
*
*/
public class MyServer {

// Server hostname
static final String BIND_ADDRESS = "localhost";
// Server port
static 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: