打个 hadoop RPC的栗子

以豁达和宽容的心态对待学习和生活中遇到的不如意的事。

需求

通过RPC远程调用服务端函数来实现加法操作

maven 依赖

依赖如下:

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

定义RPC通信功能接口

定义如下:

package inter;

import org.apache.hadoop.ipc.VersionedProtocol;

import java.io.IOException;

public interface ClientProtocol extends VersionedProtocol {
    public static final long versionID = 1L;
int add(int v1, int v2) throws IOException;
}

接口实现

实现如下:

package impl;

import inter.ClientProtocol;
import org.apache.hadoop.ipc.ProtocolSignature;

import java.io.IOException;

public class ClientProtocolImpl implements ClientProtocol {public int add(int v1, int v2) throws IOException {
        return v1 + v2;
    }

    public long getProtocolVersion(String s, long l) throws IOException {
        return ClientProtocol.versionID;
    }

    public ProtocolSignature getProtocolSignature(String s, long l, int i) throws IOException {
        return new ProtocolSignature(ClientProtocol.versionID, null);
    }
}

服务端代码

如下:

package server;

import impl.ClientProtocolImpl;
import inter.ClientProtocol;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;

import java.io.IOException;

public class Server {
    public static void main(String[] args) throws IOException {
        RPC.Server server = new RPC.Builder(new Configuration()).setProtocol(ClientProtocol.class)
                .setInstance(new ClientProtocolImpl()).setBindAddress("localhost")
                .setPort(9999)
                .setNumHandlers(5)
                .build();
        server.start();
    }
}

客户端代码

如下:

package client;

import inter.ClientProtocol;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;

import java.io.IOException;
import java.net.InetSocketAddress;

public class Client {
    public static void main(String[] args) throws IOException {
        ClientProtocol proxy = RPC.getProxy(ClientProtocol.class,
                ClientProtocol.versionID,
                new InetSocketAddress("localhost", 9999),
                new Configuration());
        System.out.println("proxy.add(1,2) = " + proxy.add(1, 2));
    }
}

 

总结

用户只需要实现四部分:RPC行为接口定义,服务端RPC接口行为实现,客户端实现,服务端实现就可以来使用RPC了。

posted @ 2020-04-01 21:08  JohnnyBai  阅读(247)  评论(0编辑  收藏  举报