RPC框架使用

一、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文件,用于启动服务
        <!--服务注组件-->
        <bean id="serviceRegistry" class="rpc.server.registry.ZkServiceRegistryImpl">
        <constructor-arg name="registryAddress" value="127.0.0.1:2181"/>
    </bean>
     <!--服务启组件 -->
    <bean id="rpcServer" class="rpc.server.ExtRpcServer">
        <property name="serviceRegistry" ref="serviceRegistry" />
    </bean>

     <!--rpc服务-->
    <bean id="httpDemo" class="rpc.junit.HttpServiceDemoImpl"/>

根据以上三步即可发布一个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
        <!--服务发现组件-->
        <bean id="serviceDiscovery" class="rpc.client.discover.ZKServiceDiscovery">
        <constructor-arg name="registryAddress" value="${com.techstar.zkservers}"/>
    </bean>
        <!--rpc服务代理-->
    <bean id="proxy" class="rpc.client.proxy.RpcProxy">
        <constructor-arg name="serviceDiscovery" ref="serviceDiscovery"/>
    </bean>

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

点击下载源码

猜你喜欢

转载自muruiheng.iteye.com/blog/2394161