Java通过Hadoop实现RPC通讯简单实例

版权声明:本文为IT晓白博主原创文章,转载请附上博文链接! https://blog.csdn.net/qq_38617531/article/details/83548324

准备pom文件中的maven依赖:jar包

<!--ipc通信模块-->
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-common</artifactId>
    <version>2.7.5</version>
</dependency>

一、定义server端代码

1.定义一个接口,该接口继承org.apache.hadoop.ipc.VersionedProtocol接口

import org.apache.hadoop.ipc.VersionedProtocol;

/**
 * 1.服务器定义接口
 */
public interface HelloServer extends VersionedProtocol {
    //版本号--用于通信暗号
    long versionID= 123L;
    String sayHello(String name);
}

2.定义实现以上接口的实现类

import org.apache.hadoop.ipc.ProtocolSignature;

import java.io.IOException;

/**
 * 2.定义接口实现类
 */
public class HelloServiceImpl implements HelloServer {
    public String sayHello(String name) {
        return "hello: "+name;
    }

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

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

3.测试开启一个服务端:用于暴露端口

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

import java.io.IOException;

/**
 * 暴露接口
 */
public class HelloService {
    public static void main(String[] args) throws IOException {
        HelloServiceImpl instance = new HelloServiceImpl();
        // 创建一个RPC builder
        RPC.Builder builder = new RPC.Builder(new Configuration());

        //指定RPC Server的参数
        builder.setBindAddress("localhost");
        builder.setPort(7788);

        //将自己的程序部署到server上
        builder.setProtocol(HelloServer.class);
        builder.setInstance(instance);

        //创建Server
        RPC.Server server = builder.build();

        //启动服务
        server.start();
        System.out.println("server is start");
    }
}

二、客户端代码

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

public class HelloClient {
    public static void main(String[] args) throws IOException {
        /**
         * HelloServer:服务端接口类
         * 123L:通信发暗号
         * InetSocketAddress:服务端地址
         * Configuration:
         */
        HelloServer proxy = RPC.getProxy(HelloServer.class, 123L, new InetSocketAddress("localhost", 7788), new Configuration());
        String result = proxy.sayHello("tom");
        System.out.println("结果是: "+result);

    }
}

三、测试

首先开启服务端--HelloService

开启客户端-提交任务--HelloClient

猜你喜欢

转载自blog.csdn.net/qq_38617531/article/details/83548324