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

posted @ 2019-10-15 20:52  Nucky_yang  阅读(321)  评论(0编辑  收藏  举报