---
title: "RPC框架使用"
author: "muruiheng"
date: "2017-09-22T16:13:48Z"
tags: []
categories: ["企业架构"]
slug: "rpc"
draft: false
lastmod: "2017-09-22T16:13:48Z"
id: 2394161
url: "https://muruiheng.iteye.com/blog/2394161"
---

**一、RPC服务开发**

本节介绍如何开发一个RPC的服务  
**## 1.1 定义接口**  
package rpc.junit;

public interface HttpServiceDemo {

    public String helloword(String name);  
}  
\## 1.2 根据接口实现服务  
在这一步，需要注意两点：一、必须实现某一个接口， 二、必须添加注解@HttpService 或 @TcpService， 同时需要说明用户实现的是哪一个接口

例如：@HttpService(HttpServiceDemo.class)

以下为示例代码：

package rpc.junit;

import rpc.common.annotation.HttpService;

@HttpService(HttpServiceDemo.class)  
public class HttpServiceDemoImpl implements HttpServiceDemo{

    @Override  
    public String helloword(String name) {  
        // TODO Auto-generated method stub  
        String result = "hello "+ name;  
        return result;  
    }

}

**## 1.3 配置Spring的xml文件，用于启动服务**  
        &lt;!--服务注组件--&gt;  
        &lt;bean id="serviceRegistry" class="rpc.server.registry.ZkServiceRegistryImpl"&gt;  
        &lt;constructor-arg name="registryAddress" value="127.0.0.1:2181"/&gt;  
    &lt;/bean&gt;  
     &lt;!--服务启组件 --&gt;  
    &lt;bean id="rpcServer" class="rpc.server.ExtRpcServer"&gt;  
        &lt;property name="serviceRegistry" ref="serviceRegistry" /&gt;  
    &lt;/bean&gt;

     &lt;!--rpc服务--&gt;  
    &lt;bean id="httpDemo" class="rpc.junit.HttpServiceDemoImpl"/&gt;

根据以上三步即可发布一个RPC服务

 

 

# 二、RPC客户端开发

**## 2.1 引入服务端的接口**  
引入服务端提供的jar文件，该文件中需要包含服务端所实现的接口

**## 2.2 开发代码**  
客户端通过rpc-client中的RpcProxy类创建一个rpc的代理类，用于实现rpc服务调用功能，这样就能像调用本地代码一样调用远程的rpc服务

package rpc.demo.client;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.test.context.ContextConfiguration;  
import rpc.client.proxy.RpcProxy;  
import rpc.junit.HttpServiceDemo;

public class HttpClientDemo {

    @Autowired  
    private RpcProxy proxy;

     
     
    /\**  
     * @param proxy the proxy to set  
     \*/  
    public void setProxy(RpcProxy proxy) {  
        this.proxy = proxy;  
    }

    public void testHttp() {  
        HttpServiceDemo httpDemo = this.proxy.create(HttpServiceDemo.class);  
        String result = httpDemo.helloword("HTTP");  
        System.out.println(result);  
    }  
     
}  
**## 2.3 配置Spring的xml**  
        &lt;!--服务发现组件--&gt;  
        &lt;bean id="serviceDiscovery" class="rpc.client.discover.ZKServiceDiscovery"&gt;  
        &lt;constructor-arg name="registryAddress" value="${com.techstar.zkservers}"/&gt;  
    &lt;/bean&gt;  
        &lt;!--rpc服务代理--&gt;  
    &lt;bean id="proxy" class="rpc.client.proxy.RpcProxy"&gt;  
        &lt;constructor-arg name="serviceDiscovery" ref="serviceDiscovery"/&gt;  
    &lt;/bean&gt;

以上三步及可完成rpc服务调用

 

[点击下载源码](https://github.com/muruiheng/rpc "rpc源码")