在了解hadoop的rpc框架之前,先尝试怎么使用它。
(请务必注意:这里使用的是hadoop2.6版本)
第一步:定义RPC协议并实现它
//定义我们的接口 实现VersionedProtocol接口
//add和sub是两个自定义方法,与当前主题无关,我们根据自己的需要去编码即
//可
//注意:这里需要使用注解 表明版本号,服务端版本号必须和客户端版本号一致
//才可以实现通信
@ProtocolInfo(protocolName = "",protocolVersion = 1L )
public interface MyProtocol extends VersionedProtocol {
public static final long versionID = 1L;
public IntWritable add(IntWritable arg1, IntWritable arg2);
public IntWritable sub(IntWritable arg1, IntWritable arg2);
}
//定义一个实现类
public class MyServerImp implements MyProtocol
第二步:服务端启动
Server server = new RPC.Builder(new Configuration())
.setProtocol(MyProtocol .class)
.setBindAddress("127.0.0.1")
.setPort(IPC_PORT)
.setInstance(new MyServerImp())
.build();
server.start();
第三步:客户端
InetSocketAddress addr = new InetSocketAddress("127.0.0.1",
IPC_PORT);
MyProtocol service = (MyProtocol)RPC.getProxy(
MyProtocol.class,
MyProtocol.versionID,
addr,
new Configuration());
从上面的例子可以看到
- RPC.Builder封装各种参数,并提供返回server对象的方法build
- org.apache.hadoop.ipc.VersionedProtocol 接口是RPC框架的顶层接口
- RPC.getProxy返回代理对象实例