1.接口
用于提供服务器和客户端的接口
package com.rpc;
import java.io.IOException;
import org.apache.hadoop.ipc.VersionedProtocol;
/*
* IProxyProtocol 通信接口
*/
public interface IProxyProtocol extends VersionedProtocol {
//版本号,默认情况下,不同版本号的RPC客户端与Server之间不能相互通信
public static final long versionID = 1L;
public String hello(String msg) throws IOException;
}
2.接口实现
实现接口内的方法
package com.rpc;
import java.io.IOException;
import org.apache.hadoop.ipc.ProtocolSignature;
/*
* 实现RPC现已接口
*/
public class MyProxy implements IProxyProtocol{
@Override
public long getProtocolVersion(String protocol, long clientVersion)
throws IOException {
return versionID;
}
@Override
public ProtocolSignature getProtocolSignature(String protocol,
long clientVersion, int clientMethodsHash) throws IOException {
return new ProtocolSignature(versionID, null);
}
@Override
public String hello(String msg) throws IOException {
return "hello " + msg;
}
}
3.服务器端实现
创建服务器时指定服务器引用的接口和接口实现。
package com.rpc;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.Server;
/*
* 构造RPC Server并启动服务
*/
public class MyServer {
private static final String HOST = "localhost";
private static final int PORT = 2181;
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
Server server = new RPC.Builder(conf).setProtocol(IProxyProtocol.class)
.setInstance(new MyProxy()).setBindAddress(HOST)
.setNumHandlers(2)
.setPort(PORT).build();
server.start();
}
}
4.客户端实现
获取接口和服务器
package com.rpc;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;
/*
* 客户端实现
*/
public class MyClient {
private static final String HOST = "localhost";
private static final int PORT = 2181;
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
IProxyProtocol proxy = RPC.getProxy(IProxyProtocol.class, IProxyProtocol.versionID,
new InetSocketAddress(HOST, PORT), conf);
String result = proxy.hello("world");
System.out.println(result);
}
}
服务器结果
客户端结果