服务调用方案(Spring Http Invoker) - 我们到底能走多远系列(40)
我们到底能走多远系列(40)
扯淡:
判断是否加可以效力于这家公司,一个很好的判断是,接触下这公司工作几年的员工,了解下生活工作状态,这就是你几年后的状态,如果满意就可以考虑加入了。
主题:
场景:项目A作为主项目,业务实现完整,项目B需要调用项目A中的部分服务,那么项目A就需要提供出服务出来。实现分布式调用的方法有很多,这里介绍一下利用Spring Http Invoker 来实现的服务提供和调用。
demo地址:摸我
如果你对快速用springmvc搭建web应用感兴趣:摸我
阅读Spring的源码基本的流程实现是这样的:

下面就详细分析一下这个流程的实现:
<bean id="remoteDemoService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl">
<value>http://localhost:7777/remote/demoService</value>
</property>
<property name="serviceInterface">
<value>com.witown.open.demo.remote.service.DemoService</value>
</property>
</bean>
首先看的是HttpInvokerProxyFactoryBean类,它继承FactoryBean,所以先来看一看这个FactoryBean。
public class HttpInvokerProxyFactoryBean extends HttpInvokerClientInterceptor
implements FactoryBean<Object> {
// 代理对象
private Object serviceProxy;
// 初始化后执行方法
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (getServiceInterface() == null) {
throw new IllegalArgumentException("Property 'serviceInterface' is required");
} // 使用AOP代理工厂创建代理对象,对这个代理对象的所有方法调用最后都会被拦截
// 调用接口的任何一个方法时都会被拦截去变成http请求
this.serviceProxy = new ProxyFactory(getServiceInterface(), this).getProxy(getBeanClassLoader());
}
// 获得bean方法
public Object getObject() {
return this.serviceProxy;
}
public Class<?> getObjectType() {
return getServiceInterface();
}
public boolean isSingleton() {
return true;
}
}
这样DemoService 的调用都会被HttpInvokerClientInterceptor拦截,拦截的方法调用会去执行HttpInvokerClientInterceptor中的invoke方法,这个方法明了的体现了客户端的执行流程的三个步骤:
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
if (AopUtils.isToStringMethod(methodInvocation.getMethod())) {
return "HTTP invoker proxy for service URL [" + getServiceUrl() + "]";
}
// 1,把方法执行信息封装成RemoteInvocation
RemoteInvocation invocation = createRemoteInvocation(methodInvocation);
RemoteInvocationResult result = null;
try {
// 2,发起http请求,把方法执行信息传过去,正常的话,服务器会返回结果
result = executeRequest(invocation, methodInvocation);
}
catch (Throwable ex) {
throw convertHttpInvokerAccessException(ex);
}
try {
// 3,解析返回的结果,转化成java对象
return recreateRemoteInvocationResult(result);
}
catch (Throwable ex) {
if (result.hasInvocationTargetException()) {
throw ex;
}
else {
throw new RemoteInvocationFailureException("Invocation of method [" + methodInvocation.getMethod() +
"] failed in HTTP invoker remote service at [" + getServiceUrl() + "]", ex);
}
}
}
public class RemoteInvocation implements Serializable {
//方法名
private String methodName;
// 类
private Class[] parameterTypes;
// 参数
private Object[] arguments;
// 步骤1中实际就是调用了这个构造函数而已
public RemoteInvocation(MethodInvocation methodInvocation) {
this.methodName = methodInvocation.getMethod().getName();
this.parameterTypes = methodInvocation.getMethod().getParameterTypes();
this.arguments = methodInvocation.getArguments();
}
// ...
}
public final RemoteInvocationResult executeRequest(HttpInvokerClientConfiguration config, RemoteInvocation invocation) throws Exception {
// RemoteInvocation(远程调用对象),转成可以传输的OutputStream,以便写入http请求中
ByteArrayOutputStream baos = getByteArrayOutputStream(invocation);
if (logger.isDebugEnabled()) {
logger.debug("Sending HTTP invoker request for service at [" + config.getServiceUrl() +
"], with size " + baos.size());
}
// 将流写入http请求,发送请求,并接收响应
return doExecuteRequest(config, baos);
}
继续追踪getByteArrayOutputStream方法,发现使用了ObjectOutputStream最终调用了writeObject方法来将对象转化成流,下面是一段ObjectOutputStream的描述:
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos)
throws IOException, ClassNotFoundException {
// 打开远程的HTTP连接
HttpURLConnection con = openConnection(config); // 设置HTTP连接信息
prepareConnection(con, baos.size()); // 把准备好的序列化的远程方法调用对象的字节流写入到HTTP请求体中
writeRequestBody(config, con, baos); // 校验HTTP响应
validateResponse(config, con); // 获得HTTP相应体的流对象
InputStream responseBody = readResponseBody(config, con);
// 读取远程调用结果对象并返回
return readRemoteInvocationResult(responseBody, config.getCodebaseUrl());
}
最后的读取远程调用结果对象并返回:
protected RemoteInvocationResult doReadRemoteInvocationResult(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
// 获得Object
Object obj = ois.readObject();
if (!(obj instanceof RemoteInvocationResult)) {
throw new RemoteException("Deserialized object needs to be assignable to type [" +
RemoteInvocationResult.class.getName() + "]: " + obj);
}
// 服务端对返回的对象封装成RemoteInvocationResult!
return (RemoteInvocationResult) obj;
}
到这里基本完成了,客户端请求远程对象方法的流程。
<servlet>
<servlet-name>remote</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/remote-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>remote</servlet-name>
<url-pattern>/remote/*</url-pattern>
</servlet-mapping>
remote-servlet.xml文件中配置了处理请求的service:
< bean name= "/demoService" class ="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter" >
< property name= "service" ref = "demoServiceImpl"/>
< property name= "serviceInterface" value ="com.witown.open.demo.service.DemoService" />
</bean >
HttpInvokerServiceExporter继承了HttpRequestHandler,所以请求从handleRequest方法开始。
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { try {
// 解析请求,获得RemoteInvocation
RemoteInvocation invocation = readRemoteInvocation(request);
// 根据RemoteInvocation里的信息:方法,参数,执行,把返回的结果封装成RemoteInvocationResult
RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy());
// 把结果写入响应
writeRemoteInvocationResult(request, response, result);
}
catch (ClassNotFoundException ex) {
throw new NestedServletException("Class not found during deserialization", ex);
}
}
内部调用的代码经过前面请求调用发起的流程学习,就会很好理解了。
至此,整个流程就完整了。
让我们继续前行
----------------------------------------------------------------------
努力不一定成功,但不努力肯定不会成功。
服务调用方案(Spring Http Invoker) - 我们到底能走多远系列(40)的更多相关文章
- 定时任务管理中心(dubbo+spring)-我们到底能走多远系列47
我们到底能走多远系列47 扯淡: 又是一年新年时,不知道上一年你付出了多少,收获了多少呢?也许你正想着老板会发多少奖金,也许你正想着明年去哪家公司投靠. 这个时间点好好整理一下,思考总结一下,的确是个 ...
- Spring mvc源码url路由-我们到底能走多远系列(38)
我们到底能走多远系列38 扯淡: 马航的事,挺震惊的.还是多多珍惜身边的人吧. 主题: Spring mvc 作为表现层的框架,整个流程是比较好理解的,毕竟我们做web开发的,最早也经常接触的就是一个 ...
- Bean实例化(Spring源码阅读)-我们到底能走多远系列(33)
我们到底能走多远系列(33) 扯淡: 各位: 命运就算颠沛流离 命运就算曲折离奇 命运就算恐吓着你做人没趣味 别流泪 心酸 更不应舍弃 ... 主题: Spring源码阅读还在继 ...
- 初始化IoC容器(Spring源码阅读)-我们到底能走多远系列(31)
我们到底能走多远系列(31) 扯淡: 有个问题一直想问:各位你们的工资剩下来会怎么处理?已婚的,我知道工资永远都是不够的.未婚的你们,你们是怎么分配工资的? 毕竟,对自己的收入的分配差不多体现了自己的 ...
- JMS生产者+单线程发送-我们到底能走多远系列(29)
我们到底能走多远系列(29) 扯淡: “然后我俩各自一端/望着大河弯弯/终于敢放胆/嘻皮笑脸/面对/人生的难” --- <山丘> “迎着风/迎向远方的天空/路上也有艰难/也有那解 ...
- node实现http上传文件进度条 -我们到底能走多远系列(37)
我们到底能走多远系列(37) 扯淡: 又到了一年一度的跳槽季,相信你一定准备好了,每每跳槽,总有好多的路让你选,我们的未来也正是这一个个选择机会组合起来的结果,所以尽可能的找出自己想要的是什么再做决定 ...
- node模拟http服务器session机制-我们到底能走多远系列(36)
我们到底能走多远系列(36) 扯淡: 年关将至,总是会在一些时间节点上才感觉时光飞逝,在平时浑浑噩噩的岁月里都浪费掉了太多的宝贵.请珍惜! 主题: 我们在编写http请求处理和响应的代码的时 ...
- Sharded实现学习-我们到底能走多远系列(32)
我们到底能走多远系列(32) 扯淡: 工作是容易的赚钱是困难的 恋爱是容易的成家是困难的 相爱是容易的相处是困难的 决定是容易的可是等待是困难的 主题: 1,Sharded的实现 Sharded ...
- Spring3整合Hibernate4-我们到底能走多远系列(30)
我们到底能走多远系列(30) 扯淡: 30篇啦!从2012-08-15开始的系列,东平西凑将近一年的时间也就这么几篇.目标的100篇,按这个速度也要再搞两年呢. 发博客果然不是件容易的事,怪不得更多的 ...
随机推荐
- web开发-服务器Controller到前端中的数据传递
一, ajax方式 (一)controller中 1. 定义AjaxResponse类 成员有: status , message, data. 其中 status是成功或失败状态, message ...
- 绑定本地Service并与之通信-----之一
import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os. ...
- [开发笔记]-Visual Studio 2012中为创建的类添加注释的模板
为类文件添加注释,可以让我们在写代码时能够方便的查看这个类文件是为了实现哪些功能而写的. 一:修改类文件模板 找到类模版的位置:C:\Program Files (x86)\Microsoft Vis ...
- 在同一个页面中加载多个不同的jQuery版本
<!-- 从谷歌服务器加载jQuery最新版本--> <script type="text/javascript" src="http://ajax.g ...
- Android调用Sqlite数据库时自动生成db-journal文件的原因
数据库为了更好实现数据的安全性,一半都会有一个Log文件方便数据库出现意外时进行恢复操作等.Sqlite虽然是一个单文件数据库,但麻雀虽小五脏俱全,它也会有相应的安全机制存在 这个journal文件便 ...
- 创建plist文件
可以先在工程中直接新建一个plist文件,往里面写入自己需要的数据.但是这里的plist文件我们无法修改,是只读的,我们可以将这个plist文件复制一份到沙盒中,然后对沙盒中的文件进行操作.具体代码如 ...
- opencv 工程的保存
一个项目的保存,只要保存工程底下的.CPP .h .dll .lib 输入输出文件即可 最终保存的文件
- ios上传应用后,审核流程完成前(reveiw)修改了程序内容,如何上传替换
其实挺简单,只需要更改下version和build版本 看图说话就可以.我的程序之前版的版本设置 修改bug之后的设置: 然后重新打包就好了,提示打包成功后,在itunesconnect查看发现 选中 ...
- linux下文件系统的介绍
一.linux文件系统的目录结构 目录 描述 / 根目录 /bin 做为基础系统所需要的最基础的命令就是放在这里.比如 ls.cp.mkdir等命令:功能和/usr/bin类似,这个目录中的文件都是可 ...
- cf--1C
//Accepted 0 KB 60 ms //给出正多变形上的三个点,求正多形的最小面积 //记三个点之间的距离a,b,c; //由余弦定理得cosA //从而可求出sinA,和正多边形所在外接圆的 ...