---
title: "远程服务调用框架设计与实现"
author: "wxyfighting"
date: "2007-11-12T08:54:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2013-05-01T13:33:06Z"
id: 1858077
url: "https://wxyfighting.iteye.com/blog/1858077"
---

远程服务调用框架设计与实现

Auther: cenwenchu

Email: [wenchu.cenwc@alibaba-inc.com](mailto:wenchu.cenwc@alibaba-inc.com)

Version: 0.1

Date: &lt;chsdate style="BACKGROUND-POSITION: left bottom; BACKGROUND-IMAGE: url(res://ietag.dll/#34/#1001); BACKGROUND-REPEAT: repeat-x" tabindex="" w:st="on" isrocdate="False" islunardate="False" day="22" month="6" year="2007"&gt;2007-6-22&lt;/chsdate&gt;

SVN: [http://svn.alibaba-inc.com/repos/opentech/sandbox/remoting/trunk](http://svn.alibaba-inc.com/repos/opentech/sandbox/remoting/trunk)

[目的... 2]()

[实现技术... 2]()

[接口定义和实现规范... 2]()

[设计实现... 3]()

[基本类图... 3]()

[基本流程图... 4]()

[具体的配置和使用... 4]()

# [目的]()

为远程服务调用提供统一的框架，该框架集中解决远程调用过程中的三方面问题：

a. 应用透明性：应用的接口和实现不依赖于框架的实现。框架可以透明的切换各种远程调用技术，而上层应用的接口和实现不用做任何调整。

b. 安全性：安全性主要包括两个方面：身份及签名验证(防篡改伪造)；数据传输保密性(防监听)；IP认证。

c. 调用频度控制：为保证服务可用，需要对于调用频度根据一定的规则进行控制。

# [实现技术]()

由于调用双方都是基于Java的应用，实现技术上建议采用基于Spring的Remoting框架，这样可以实现应用透明性，接口开发人员不用考虑远程调用等与业务无关的技术细节。基于Spring框架并进行扩展，我们可以在框架层次实现安全性和调用频度限制。

由于调用双方不在一个局域网环境内，因此在具体通讯协议上，最佳选择即为Http。因此我们推荐的实现技术包括：Spring Remoting + Spring HttpInvoker，以及Spring Remoting + Hessian。

安全性包括身份验证和数据传输安全两个方面，身份验证可以根据调用双方的信任程度以及性能要求确定采用对称加密或者非对称加密，当前提供了三种验证措施，用户名加密认证，IP认证，以及消息数字摘要加密验证，该验证可以在Spring Remoting基础上进行扩展。数据传输安全则主要是担心数据在传输过程中被截获，对于基于Http的传输，使用Https即可(无需在框架或者应用层支持)。

调用频度控制，则可以应用AOP技术，对于调用进行截获和统计，根据一定的规则，判断调用是否符合控制策略。

# [接口定义和实现规范]()

接口定义和实现为简单的POJI和POJO即可，不过为了满足远程调用的需要，需要保证所有参数和返回值都是可序列化的，另外，鉴于部分远程调用技术的序列化机制的特殊性(例如Hessian)，数据类型应尽可能简单。此外，基于性能考虑，远程接口调用方式适用于中低频度的小数据量的调用，对于大批量数据同步或者相当高频度的调用，远程接口调用方式并不合适。

# [设计实现]()

## [基本类图]()

&lt;shapetype id="\_x0000\_t75" stroked="f" filled="f" path=" m@4@5 l@4@11@9@11@9@5 xe" o:preferrelative="t" o:spt="75" coordsize="21600,21600"&gt;&lt;stroke joinstyle="miter"&gt;&lt;/stroke&gt;&lt;formulas&gt;&lt;f eqn="if lineDrawn pixelLineWidth 0 "&gt;&lt;/f&gt;&lt;f eqn="sum @0 1 0 "&gt;&lt;/f&gt;&lt;f eqn="sum 0 0 @1 "&gt;&lt;/f&gt;&lt;f eqn="prod @2 1 2 "&gt;&lt;/f&gt;&lt;f eqn="prod @3 21600 pixelWidth "&gt;&lt;/f&gt;&lt;f eqn="prod @3 21600 pixelHeight "&gt;&lt;/f&gt;&lt;f eqn="sum @0 0 1 "&gt;&lt;/f&gt;&lt;f eqn="prod @6 1 2 "&gt;&lt;/f&gt;&lt;f eqn="prod @7 21600 pixelWidth "&gt;&lt;/f&gt;&lt;f eqn="sum @8 21600 0 "&gt;&lt;/f&gt;&lt;f eqn="prod @7 21600 pixelHeight "&gt;&lt;/f&gt;&lt;f eqn="sum @10 21600 0 "&gt;&lt;/f&gt;&lt;/formulas&gt;&lt;path o:connecttype="rect" gradientshapeok="t" o:extrusionok="f"&gt;&lt;/path&gt;&lt;lock aspectratio="t" v:ext="edit"&gt;&lt;/lock&gt;&lt;/shapetype&gt;&lt;shape id="\_x0000\_i1026" style="WIDTH: 414.75pt; HEIGHT: 387.75pt" coordsize="21600,21600" type="#\_x0000\_t75"&gt;&lt;imagedata o:title="" src="D68C4E15.files/image001.emz"&gt;&lt;/imagedata&gt;&lt;/shape&gt;

![](http://p.blog.csdn.net/images/p_blog_csdn_net/cenwenchu79/image0021.gif)

图1 远程服务发布类结构图

针对Hessian和HttpInvoker两种远程服务调用的方式封装了对于安全控制的两个安全发布类，具体的安全配置以及安全操作都在RemoteContractTemplate中，这样可以方便扩展任何安全的需求变更，并且对原有任何的Exporter做了安全切面处理，防止过度耦合。

&lt;shape id="\_x0000\_i1027" style="WIDTH: 414.75pt; HEIGHT: 336.75pt" coordsize="21600,21600" type="#\_x0000\_t75"&gt;&lt;imagedata o:title="" src="D68C4E15.files/image003.emz"&gt;&lt;/imagedata&gt;&lt;/shape&gt;

![](http://p.blog.csdn.net/images/p_blog_csdn_net/cenwenchu79/image0041.gif)

图 2 远程服务调用类结构图

远程服务调用对于不同的方法调用需要不同的定制，这里针对Hessian和HttpInvoker采用了替换植入内部处理类的方式，Hessian植入了新的HessianProxyFactory用来生成新的HessianProxy来植入安全机制，HttpInvokerFactoryBean植入了新的HttpInvokerRequestExecutor来植入安全机制，同样安全配置以及操作都封装在RemoteContractTemplate中，集中控制和配置，方便扩展和管理。

## [基本流程图]()

&lt;shape id="\_x0000\_s2196" style="WIDTH: 375.8pt; HEIGHT: 636.9pt; mso-position-horizontal-relative: char; mso-position-vertical-relative: line" coordsize="21600,21600" type="#\_x0000\_t75"&gt;&lt;imagedata o:title="flow" src="D68C4E15.files/image005.jpg"&gt;&lt;/imagedata&gt;&lt;wrap type="none"&gt;&lt;/wrap&gt;&lt;anchorlock&gt;&lt;/anchorlock&gt;&lt;/shape&gt;

![](http://p.blog.csdn.net/images/p_blog_csdn_net/cenwenchu79/image0051.jpg)

图 3 基本流程图

如上图所示，用户发起请求调用远程服务，首先是创建远程服务代理，然后通过植入安全信息将请求发送到远程服务发布处理类中，首先检查安全信息，如果通过安全检测就进入方法调用拦截器中检验类似于频率之类的限制过程中，通过拦截器的检测就可以调用真正的远程服务，并且获得结果，将结果返回并封装安全信息返回给服务调用代理，代理首先检测是否有合法的安全信息，如果通过安全信息认证，将结果返回给客户端。

## [具体的配置和使用]()

这里通过一个Demo来说明如何使用这个远程服务调用框架。

假定一个售票管理服务要发布，售票管理服务结构图如下：

&lt;shape id="\_x0000\_i1028" style="WIDTH: 291pt; HEIGHT: 237.75pt" coordsize="21600,21600" type="#\_x0000\_t75"&gt;&lt;imagedata o:title="" src="D68C4E15.files/image007.emz"&gt;&lt;/imagedata&gt;&lt;/shape&gt;

![](http://p.blog.csdn.net/images/p_blog_csdn_net/cenwenchu79/image0081.gif)

图 4 售票管理服务结构图

服务类接口为TicketManage，实现类是TicketManageImpl。测试调用类为TicketManageClient。接口和接口的实现类就是按照普通的Java规范来实现即可，TicketManageClient根据你选择不同的服务调用方式来编写代码，这里用到了Hessian和HttpInvoker两种方式，代码如下：

**public** **static** **void** main(String\[] args)

{

ApplicationContext ctx = **new** ClassPathXmlApplicationContext("ticket.xml");

TicketManage ticketManage = (TicketManage)ctx.getBean("ticketService");//hession调用的配置

Ticket ticket = ticketManage.buyTicket(20);

System.*out*.println("ticket seat: " + ticket.getSeat());

**int** returncost = ticketManage.returnTicket(ticket);

System.*out*.println("return ticket, get back cost :" + returncost);

TicketManage httpTicketManage = (TicketManage)ctx.getBean("ticketHttpService");//HttpInvoke调用的配置

ticket = httpTicketManage.buyTicket(30);

System.*out*.println("ticket seat: " + ticket.getSeat());

returncost = httpTicketManage.returnTicket(ticket);

System.*out*.println("return ticket, get back cost :" + returncost);

}

ticket.xml是客户端的spring配置文件，具体的内容如下：

&lt;?xml version="1.0" encoding="GB2312"?&gt;

&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt;

&lt;beans default-autowire="byName"&gt;

&lt;!—- 安全模版配置类，参数在后面会有详细解释 --&gt;

&lt;bean id="remoteContractTemplate" class="com.alibaba.common.remoting.util.RemoteContractTemplate" init-method="init"&gt;

&lt;property name="encryptKeyPath" value="file:c://key.ky" /&gt;

&lt;property name="decryptKeyPath" value="file:c://key.ky" /&gt;

&lt;property name="algonrithm" value="RSA"/&gt;

&lt;property name="needMD" value="true"/&gt;

&lt;property name="needUserAuth" value="true"/&gt;

&lt;property name="user"&gt;

&lt;list&gt;

&lt;value&gt;taobao&lt;/value&gt;

&lt;value&gt;zhifubao&lt;/value&gt;

&lt;value&gt;b2b&lt;/value&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;property name="owner" value="alisoft"/&gt;

&lt;property name="connectTimeout" value="6"/&gt;

&lt;property name="readTimeout" value="0"/&gt;

&lt;property name="needIPAuth" value="true"/&gt;

&lt;property name="ipList"&gt;

&lt;list&gt;

&lt;value&gt;&lt;chsdate w:st="on" isrocdate="False" islunardate="False" day="30" month="12" year="1899"&gt;10.0.26&lt;/chsdate&gt;.23&lt;/value&gt;

&lt;value&gt;&lt;chsdate w:st="on" isrocdate="False" islunardate="False" day="30" month="12" year="1899"&gt;10.0.0&lt;/chsdate&gt;.42&lt;/value&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;/bean&gt;

&lt;!—- 需要植入到HttpInvokerProxyFactoryBean的安全请求处理类 --&gt;

&lt;bean id="securityHttpInvokerRequestExecutor" class="com.alibaba.common.remoting.http.SecurityHttpInvokerRequestExecutor"&gt;

&lt;property name="remoteContractTemplate" ref="remoteContractTemplate" /&gt;

&lt;/bean&gt;

&lt;!—- 发布服务的Bean --&gt;

&lt;bean id="ticketHttpService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"&gt;

&lt;property name="serviceUrl" value="http://localhost:80/remote-examples/remote/TicketHttpService"/&gt;

&lt;property name="serviceInterface" value="com.alibaba.common.remoting.test.TicketManage"/&gt;

&lt;property name="httpInvokerRequestExecutor" ref="securityHttpInvokerRequestExecutor"/&gt;

&lt;/bean&gt;

&lt;!—- Hessian的安全代理工厂类Bean --&gt;

&lt;bean id="securityHessianProxyFactory" class="com.alibaba.common.remoting.hessian.SecurityHessianProxyFactory"&gt;

&lt;property name="remoteContractTemplate" ref="remoteContractTemplate" /&gt;

&lt;/bean&gt;

&lt;bean id="ticketService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean"&gt;

&lt;property name="serviceUrl" value="http://localhost:80/remote-examples/remote/TicketService"/&gt;

&lt;property name="serviceInterface" value="com.alibaba.common.remoting.test.TicketManage"/&gt;

&lt;property name="proxyFactory" ref="securityHessianProxyFactory"/&gt;

&lt;/bean&gt;

&lt;/beans&gt;

上面的xml中蓝色的内容需要根据具体的情况作修改，黑色的内容则不需要修改。

安全模版配置类参数具体说明：下面是代码中的说明，大家一看就应该明白了

**private** String encryptKeyPath;//encryptKey的路径

**private** String decryptKeyPath;//decryptKey的路径

**private** Key encryptKey;//根据encryptKey的路径生成的key

**private** Key decryptKey;//根据decryptKey的路径生成的key

**private** String algonrithm;//算法

**private** String needMD;//是否需要MD校验

**private** String needUserAuth;//是否需要加密

**private** List&lt;String&gt; user;//允许对方访问或者返回结果的用户名

**private** String owner;//自己的签名

**private** **byte**\[] encrypted;//加密后的用户签名，一次加密，多次使用，增加性能提升

**private** String encoding = "GB2312";//编码方式，加密和md的内容的编码方式

**private** String needIPAuth;//是否需要IP认证

**private** List&lt;String&gt; ipList;//允许访问的ip列表

**private** **int** readTimeout = 0;// 读取数据超时时间设置，单位秒

**private** **int** connectTimeout = 0;// 连接超时时间设置，单位秒

客户端设置好以后，就需要设置服务端了：

服务端很简单首先是类似于Spring的Hessian和HttpInvoker调用的配置一样，在WEB-INF/lib下面放入toolkit-sandbox-remoting.jar以及其它以来的jar，然后配置web.xml，增加如下内容（这都是spring mvc框架的配置，大家可以参考spring来配置）：

&lt;servlet&gt;

&lt;servlet-name&gt;remote&lt;/servlet-name&gt;

&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;

&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;

&lt;/servlet&gt;

&lt;servlet-mapping&gt;

&lt;servlet-name&gt;remote&lt;/servlet-name&gt;

&lt;url-pattern&gt;/remote/\*&lt;/url-pattern&gt;

&lt;/servlet-mapping&gt;

然后在WEB-INF下面新建remote-servlet.xml，如果要换名称，需要在上面的配置文件配置。

remote-servlet.xml内容如下：

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;beans xmlns="http://www.springframework.org/schema/beans"

xmlns:sca="http://www.springframework.org/schema/sca"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:osgi="http://www.springframework.org/schema/osgi"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/sca http://www.springframework.org/schema/sca/spring-sca.xsd http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd" default-autowire="byName"&gt;

&lt;bean id="ticketManageTarget" class="com.alibaba.common.remoting.test.TicketManageImpl" /&gt;

&lt;bean id="ticketManage" class="org.springframework.aop.framework.ProxyFactoryBean"&gt;

&lt;property name="proxyInterfaces" value="com.alibaba.common.remoting.test.TicketManage" /&gt;

&lt;property name="target"&gt;&lt;ref local="ticketManageTarget" /&gt;&lt;/property&gt;

&lt;!—- 拦截器bean --&gt;

&lt;property name="interceptorNames"&gt;

&lt;list&gt;

&lt;value&gt;remoteMethodInterceptor&lt;/value&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;/bean&gt;

&lt;bean id="remoteMethodInterceptor" class="com.alibaba.common.remoting.interceptor.RemoteCounterInterceptor" &gt;

&lt;property name="valve" value="20"/&gt;&lt;!—- 阀值代表次数 --&gt;

&lt;property name="policy" value="hour"/&gt;&lt;!—- 策略，当前提供hour,day,month三种 --&gt;

&lt;!—- 上面的配置代表了每小时不能超过20次的访问 --&gt;

&lt;/bean&gt;

&lt;bean id="remoteContractTemplate" class="com.alibaba.common.remoting.util.RemoteContractTemplate" init-method="init"&gt;

&lt;property name="encryptKeyPath" value="file:c://key.ky" /&gt;

&lt;property name="decryptKeyPath" value="file:c://key.ky" /&gt;

&lt;property name="algonrithm" value="RSA"/&gt;

&lt;property name="needMD" value="true"/&gt;

&lt;property name="needUserAuth" value="true"/&gt;

&lt;property name="user"&gt;

&lt;list&gt;

&lt;value&gt;alisoft&lt;/value&gt;

&lt;value&gt;zhifubao&lt;/value&gt;

&lt;value&gt;b2b&lt;/value&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;property name="owner" value="taobao"/&gt;

&lt;property name="connectTimeout" value="6"/&gt;

&lt;property name="readTimeout" value="0"/&gt;

&lt;/bean&gt;

&lt;!—- HttpService发布Bean,植入了安全策略配置模版 --&gt;

&lt;bean name="/TicketHttpService" class="com.alibaba.common.remoting.http.SecurityHttpInvokerServiceExporter"&gt;

&lt;property name="service" ref="ticketManage"/&gt;

&lt;property name="serviceInterface" value="com.alibaba.common.remoting.test.TicketManage"/&gt;

&lt;property name="remoteContractTemplate" ref="remoteContractTemplate" /&gt;

&lt;/bean&gt;

&lt;!—- Hessian服务发布Bean,植入了安全策略配置模版 --&gt;

&lt;bean name="/TicketService" class="org.springframework.remoting.caucho.SecurityHessianServiceExporter"&gt;

&lt;property name="service" ref="ticketManage"/&gt;

&lt;property name="serviceInterface" value="com.alibaba.common.remoting.test.TicketManage"/&gt;

&lt;property name="remoteContractTemplate" ref="remoteContractTemplate" /&gt;

&lt;/bean&gt;

&lt;/beans&gt;

最后需要做的就是生成key，当前key的算法有两种，对称加密和非对称加密，分别用AES算法和RSA算法，注意一旦产生了Key文件，双方就要使用相同的key文件，同一个用户加解密的key文件可以不一致，但是双方的解密和加密文件必须配对使用。

产生key文件的方法如下：

将toolkit-sandbox-remoting.jar所在的位置配置到classpath中，然后通过命令行执行。

生成对称加密key文件命令为：

Java com.alibaba.common.remoting.cryption.KeyGenTool genkey 文件目录 文件名

生成非对称加密key文件命令为：

Java com.alibaba.common.remoting.cryption.KeyGenTool genkeypair 文件目录 文件名

这样你分别会在文件目录中找到对应得文件，后缀名为.ky