| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
码头工人
9年前发布

Hadoop RPC使用方法示例

定义RPC协议

import java.io.IOException;    import org.apache.hadoop.ipc.VersionedProtocol;    /**   * DateTime: 2014年12月28日 上午9:32:12   *   */  public interface ClientProtocol extends VersionedProtocol {   //版本号,默认情况下,不同版本号的RPC客户端与Server之间不能相互通信   public static final long versionID = 1L;   public String hello(String msg) throws IOException;  }

实现RPC协议

import java.io.IOException;    import org.apache.hadoop.ipc.ProtocolSignature;    /**   * DateTime: 2014年12月28日 上午9:41:38   *   */  public class ClientProtocolImpl implements ClientProtocol {     @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;   }        }

构建并启动RPC Server

import java.io.IOException;    import org.apache.hadoop.conf.Configuration;  import org.apache.hadoop.ipc.RPC;  import org.apache.hadoop.ipc.RPC.Server;    /**   * DateTime: 2014年12月28日 上午9:47:05   *   */  public class RPCServer {   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(ClientProtocol.class)      .setInstance(new ClientProtocolImpl()).setBindAddress(HOST)      .setNumHandlers(2)      .setPort(PORT).build();    server.start();   }  }

构造并启动RPC Clinet并发送RPC请求

import java.io.IOException;  import java.net.InetSocketAddress;    import org.apache.hadoop.conf.Configuration;  import org.apache.hadoop.ipc.RPC;    /**   * DateTime: 2014年12月28日 上午9:52:19   *   */  public class RPCClient {   private static final String HOST = "localhost";   private static final int PORT = 2181;     public static void main(String[] args) throws IOException {    Configuration conf = new Configuration();    ClientProtocol proxy = RPC.getProxy(ClientProtocol.class, ClientProtocol.versionID,      new InetSocketAddress(HOST, PORT), conf);    String result = proxy.hello("world");    System.out.println(result);   }  }

 

 本文由用户 码头工人 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1419758087218.html
Hadoop 分布式/云计算/大数据