Hadoop RPC测试

1.接口

用于提供服务器和客户端的接口

package com.rpc;

import java.io.IOException;

import org.apache.hadoop.ipc.VersionedProtocol;
/*
 * IProxyProtocol 通信接口
 */
public interface IProxyProtocol extends VersionedProtocol {
    //版本号,默认情况下,不同版本号的RPC客户端与Server之间不能相互通信
        public static final long versionID = 1L;
        public String hello(String msg) throws IOException;
}

2.接口实现

实现接口内的方法

package com.rpc;

import java.io.IOException;

import org.apache.hadoop.ipc.ProtocolSignature;
/*
 * 实现RPC现已接口
 */
public class MyProxy implements IProxyProtocol{

    @Override
    public long getProtocolVersion(String protocol, long clientVersion)
            throws IOException {
        return versionID;
    }

    @Override
    public ProtocolSignature getProtocolSignature(String protocol,
            long clientVersion, int clientMethodsHash) throws IOException {
        return new ProtocolSignature(versionID, null);
    }

    @Override
    public String hello(String msg) throws IOException {
        return "hello " + msg;
    }

}

3.服务器端实现

创建服务器时指定服务器引用的接口和接口实现。

package com.rpc;

import java.io.IOException;

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

/*
 * 构造RPC Server并启动服务
 */
public class MyServer {
    private static final String HOST = "localhost";
    private static final int PORT = 2181;
    public static void main(String[] args) throws IOException {
        Configuration conf = new Configuration();
        Server server = new RPC.Builder(conf).setProtocol(IProxyProtocol.class)
                .setInstance(new MyProxy()).setBindAddress(HOST)
                .setNumHandlers(2)
                .setPort(PORT).build();
        server.start();
    }
}

4.客户端实现

获取接口和服务器

package com.rpc;

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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;
/*
 * 客户端实现
 */
public class MyClient {
    private static final String HOST = "localhost";
    private static final int PORT = 2181;

    public static void main(String[] args) throws IOException {
        Configuration conf = new Configuration();
        IProxyProtocol proxy = RPC.getProxy(IProxyProtocol.class, IProxyProtocol.versionID,
        new InetSocketAddress(HOST, PORT), conf);
        String result = proxy.hello("world");
        System.out.println(result);
    }

}

服务器结果

这里写图片描述

客户端结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值