• hadoop自带RPC的使用 代码demo


    引入的三方包

      <dependency>
           <groupId>org.apache.hadoop</groupId>
           <artifactId>hadoop-common</artifactId>
           <version>2.7.0</version>
      </dependency>

    引入的common包依赖了好多jar,建议用maven工程引入(不要copy到lib在add build path)。

     1.创建自己的协议版本

    import org.apache.hadoop.ipc.VersionedProtocol;
    public interface  ClientProtocol extends VersionedProtocol {
        public static final long versionID=1111L;
        String echo(String value);
    }

    2.实现协议

    import java.io.IOException;
    import org.apache.hadoop.ipc.ProtocolSignature;
    public class ClientProtocolImpl implements ClientProtocol {
    
        @Override
        public ProtocolSignature getProtocolSignature(String arg0, long arg1, int arg2) throws IOException {
            return new ProtocolSignature(ClientProtocol.versionID,null);
        }
    
        @Override
        public long getProtocolVersion(String arg0, long arg1) throws IOException {
            // TODO Auto-generated method stub
            return ClientProtocol.versionID;
        }
    
        @Override
        public String echo(String value) {
             return "hello "+value;
        }
    
    }

    3.创建并且启动server 

    import org.apache.hadoop.ipc.Server;
    
    import java.io.IOException;
    import org.apache.hadoop.HadoopIllegalArgumentException;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.ipc.RPC;
    public class MyRpcServer {
    
        public static void main(String[] args) throws HadoopIllegalArgumentException, IOException {
               Server server =new RPC.Builder(new Configuration()).setProtocol(ClientProtocol.class)
                        .setInstance(new ClientProtocolImpl()).setBindAddress("127.0.0.1").setPort(8787)
                        .setNumHandlers(5).build();
                server.start();
        }
    }

    4.创建并且启动client

    import java.io.IOException;
    import java.net.InetSocketAddress;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.ipc.RPC;
    
    public class Client {
    
        public static void main(String[] args) throws IOException {
             ClientProtocol proxy = (ClientProtocol) RPC.getProxy(ClientProtocol.class,ClientProtocol.versionID,new InetSocketAddress("127.0.0.1",8787),new Configuration());
                String result = proxy.echo("123");
                System.out.println(result);  
        }
    }

    参考:https://www.cnblogs.com/dycg/p/rpc.html

  • 相关阅读:
    浦东新区2019年下半年部分街镇社区工作者和部分单位编外人员公开招聘考试大纲
    苏州 山西
    第几行记录
    命令 检查Linux服务器性能
    SQLRecoverableException: I/O Exception: Connection reset
    Oracle单表备份三种方案
    vim 清空
    常看 Shell: 文本文件操作
    bash date format
    Linux Shell 截取字符串
  • 原文地址:https://www.cnblogs.com/yanghaolie/p/11680492.html
Copyright © 2020-2023  润新知