Hadoop基础(十一) --- RPC远程调用过程分析

一、RPC远程调用过程分析
---------------------------------------------
    1.定义协议(接口)
    
        //这个接口是所有RPC的父接口
        public interface VersionedProtocol {
    
              public long getProtocolVersion(String protocol,
                                         long clientVersion) throws IOException;
        
              public ProtocolSignature getProtocolSignature(String protocol, 
                                         long clientVersion,
                                         int clientMethodsHash) throws IOException;
            }
        }
            

/**
 * 定制协议接口
 */
public interface IHelloWordService extends VersionedProtocol{
    
    public static final long versionID = 1l;
    public String sayHello(String mag);
    
}


            

    2.创建接口的实现类

/**
 * 自定义实现接口
 * @author Administrator
 *
 */
public class HelloWorldServerImpl implements IHelloWordService {

    /**
     * 返回协议的版本号
     */
    public long getProtocolVersion(String protocol, long clientVersion) throws IOException {
        
        return versionID;
    }

    /**
     * 返回协议的签名
     */
    public ProtocolSignature getProtocolSignature(String protocol, long clientVersion, int clientMethodsHash)
            throws IOException {
        
        return new ProtocolSignature(versionID,null);
    }

    /**
     * 业务方法
     */
    public String sayHello(String msg) {
        
        System.out.println(msg);
        return "hello" + msg;
    }

}

    3.创建服务端

/**
 * 创建服务器端
 * @author Administrator
 *
 */
public class MyServer {

    public static void main(String[] args) throws Exception {
        
        //配置server
        Builder builder = new RPC.Builder(new Configuration());
        builder.setProtocol(IHelloWordService.class);
        builder.setInstance(new HelloWorldServerImpl());
        builder.setBindAddress("localhost");
        builder.setPort(7777);
        builder.setnumReaders(2);        //处理器个数
        //开始构建Server
        Server ser = builder.build();
        //启动server
        ser.start();
        
    }
}

    
    4.创建客户端

/**
 * 创建客户端
 * @author Administrator
 *
 */
public class MyClient {

    public static void main(String[] args) throws Exception {
        //设定配置文件
        Configuration conf = new Configuration();
        //开启远程代理对象,进行方法的代理
        IHelloWordService proxy = RPC.getProxy(IHelloWordService.class,
                IHelloWordService.versionID, new InetSocketAddress("localhost", 7777), conf);
        //执行代理方法
        String result = proxy.sayHello("tom cat");
        //打印代理方法的结果
        System.out.println(result);        
    }
}

    
    5.运行
        a.运行服务端
        b.运行客户端

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值