//版本接口
public interface AsopSpiderProtocol extends VersionedProtocol {
public static final long versionID = 1L;
}
//定义接口
public interface Serverif{
public String method(String args);
}
//服务器端的实现
public static class ServerImpl implements Serverif, AsopSpiderProtocol{
public long getProtocolVersion(String protocol, long clientVersion) {
return AsopSpiderProtocol.versionID;
}
//业务逻辑的实现
public String method(String args){
return args;
}
}
public static void main(String args[]) throws Exception {
ServerImpl si = new ServerImpl();
org.apache.hadoop.ipc.Server server = RPC.getServer(si,SERVERADDRESS1,SERVERPORT1, 10, true,conf);
server.start();
server.join();
}
//客户端的实现
public static class Client {
//利用代理的方式调用,如果通过代理方式getProxy,服务器只能有一个
public String method_proxy(String args) throws Exception{
InetSocketAddress sa=new InetSocketAddress(SERVERADDRESS1,SERVERPORT1);
Serverif si=(Serverif) RPC.getProxy(Serverif.class,AsopSpiderProtocol.versionID, sa, conf);
return si.method(args);
}
//利用反射的方式调用,如果通过反射方式,服务器可以有多个,
//参数为一个二维数据,相对应每个服务器的方法
public String method_reflected(String args) throws Exception{
InetSocketAddress[] sa=new InetSocketAddress[]{
new InetSocketAddress(SERVERADDRESS1,SERVERPORT1),
new InetSocketAddress(SERVERADDRESS2,SERVERPORT2)};
Para para = new Para();
para.setTaskId(111);
Object[][] params = new Object[1][1];
params[0][0] = para;
//根据反射找方法
Method METHOD = Serverif.class.getMethod("method", new Class[] {String.class});