Hadoop RPC实例

本文发表于本人博客

    上次写了个hadoop伪分布环境搭建的笔记了,今天来说下hadoop分布式构建的基础RPC,这个RPC在提交Job任务的时候底层就是创建了RPC来实现远程过程调用服务端。

    我们首先可以通过Job的waitForCompletion(boolean verbose)方法来跟踪代码,按照顺序往下查看源码,在JobClient中发现了:

      this.rpcJobSubmitClient = createRPCProxy(JobTracker.getAddress(conf), conf);
      this.jobSubmitClient = createProxy(this.rpcJobSubmitClient, conf);

我们可以发现createProxy()方法返回的是JobSubmissionProtocol接口,而这个接口实际上继承VersionedProtocol接口,可以查看这个接口的说明:

/**
 * Superclass of all protocols that use Hadoop RPC.
 * Subclasses of this interface are also supposed to have
 * a static final long versionID field.
 */

可以看到是所有hadoopRPC的协议超类。那我们来使用这个接口实现在server以及client中RPC。看下面代码:

conf文件类:

/**
 * RPC 配置
 * @author Administrator
 *
 */
public class conf {
    public static final String ADDR = "localhost";
    public static final int PORT = 9000;
    public static final long version = 123456L;
}

Operator文件类:

interface OperatorAble extends VersionedProtocol {
    /**
     * 说话
     * @param name
     * @return
     */
    public String Talk(String name);
}
public class Operator implements OperatorAble {
    /**
     * 说话
     * @param name
     * @return
     */
    @Override
    public String Talk(String name){
        System.out.println("Operator is call......");
        return "hello:" + name;
    }
    @Override
    public long getProtocolVersion(String protocol, long clientVersion) throws IOException{
          return conf.version;
    }
}

Server文件类:

/**
 * RPC 服务端
 * @author Administrator
 *
 */
public class Server {
    public static void main(String[] args) throws Exception {
        org.apache.hadoop.ipc.RPC.Server server = RPC.getServer(new Operator(), conf.ADDR, conf.PORT, new Configuration());
        server.start();
    }
}

Client文件类:

/**
 * RPC 客户端
 * @author Administrator
 *
 */
public class Client {
    
    public static void main(String[] args) throws Exception  {
        OperatorAble proxy = (OperatorAble)RPC.waitForProxy(OperatorAble.class, conf.version, new InetSocketAddress(conf.ADDR, conf.PORT), new Configuration());
        for (int i = 0; i < 100000; i++) {
            String talk = proxy.Talk("luoliang.me");
            System.out.println(talk);
        }
        RPC.stopProxy(proxy);
    }
    
}

这里特别需要注意一下的就是实现VersionedProtocol接口的时候,如果直接实现这个接口那么我可以想想在客户端怎么来通过接口调用啊,而这个VersionedProtocol接口是没有我们需要的功能,那只有重新创建一个OperatorAble接口再继承次VersionedProtocol接口了,在客户端那边使用OperatorAble来远程过程调用!当执行

String talk = proxy.Talk("luoliang.me");

时,在服务端就会输出

Operator is call......

这样表示服务端已经调用了!大家可以按照刚才的思路跟踪下去看看他们是怎么做的,这里就不说了。

这次先到这里。坚持记录点点滴滴!



原文地址:https://www.cnblogs.com/luoliang/p/4166532.html