基于HTTP请求处理器流程的实现 .

1.1.1.1             基于 HTTP 请求处理器流程的实现

这一节,我们将分析 Spring Web MVC 中的另外一个流程,它是用来支持基于 HTTP 协议的远程调用的流程。它并不是应用到一个简单的 HTTP 请求,它使用 Servlet 通过 HTTP 协议导出一个服务,服务的客户端可以通过 HTTP 协议使用和调用此服务。 Spring Web MVC 支持基于 HTTP 协议的三个类型的远程调用,基于 Burlap 的远程调用 , 基于 Hessian 的远程调用和基于序列化的远程调用。这里我们只分析基于序列化的远程调用,在后面小节中我们将分析所有远程调用流程的架构实现。

 

既然这是一个远程调用流程的实现,那么必然存在客户端和服务器端的实现,客户端是通过一个工厂 Bean 的实现导出服务器接口的代理,代理的实现把对方法的调用封装成远程调用对象并且进行序列化,通过配置的 HTTP URL 把序列化的远程调用对象通过 HTTP 请求体传入到服务器,服务器解析序列化的远程调用对象,然后通过反射调用远程调用对象里包含的方法,最后发送返回值到客户端。如下流程图所示,

 

图表 4 ‑ 23

 

首先我们深入分析基于 HTTP 请求处理器流程的远程调用的客户端的实现体系结构。如下类图所示,

 

图表 4 ‑ 24

 

客户端的实现是通过 AOP 代理拦截方法调用,然后,将传入的方法参数和正在调用的方法封装到远程调用对象并且序列化为字节流。最后,通过 HTTP 调用器请求执行器写入到远程主机的 HTTP 服务中的。下面我们根据流程的先后顺序对实现代码进行分析,如下代码注释,

 

当在客户端的 Spring 环境中配置一个 HTTP 服务,首先我们需要声明一个 HTTP 唤起器代理工厂 Bean(HttpInvokerProxyFactoryBean) ,然后指定需要代理的接口类和服务器端服务的 URL 。如下 Spring 配置文件所示,

 

  1. <bean id="httpInvokerProxy" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">   
  2.   <property name="serviceUrl" value="http://remotehost:8080/remoting/AccountService"/>  
  3.    <property name="serviceInterface" value="example.AccountService"/>   
  4. </bean>   

 

HTTP 唤起器代理工厂 Bean 实现了工厂 Bean 接口,当它被初始化后进行 Bean 连接的时候,它会提供一个代理对象。如下代码注释,

 

  1. // 这是一个工厂Bean,返回一个代理对象,用于拦截对于提供的接口方法的调用,然后,实现远程调用   
  2. public class HttpInvokerProxyFactoryBean extends HttpInvokerClientInterceptor  
  3.         implements FactoryBean<Object> {  
  4.     // 返回的代理对象   
  5.     private Object serviceProxy;  
  6.     // Spring环境中的Bean的占位符方法,初始化后属性后,构造代理对象   
  7.     @Override  
  8.     public void afterPropertiesSet() {  
  9.         super.afterPropertiesSet();  
  10.           
  11.         // 将要代理的接口为空,抛出异常,停止处理   
  12.         if (getServiceInterface() == null) {  
  13.             throw new IllegalArgumentException("Property 'serviceInterface' is required");  
  14.         }  
  15.           
  16.         // 使用AOP代理工厂创建代理对象,对这个代理对象的所有方法调用最后都会被拦截,然后调用到超类对MethodInterceptor的实现方法invoke()   
  17.         // 如果将要代理类是接口,则使用JDK的动态代理,如果将要代理类是类类型,则需要使用CGLIB产生子类创建代理   
  18.         this.serviceProxy = new ProxyFactory(getServiceInterface(), this).getProxy(getBeanClassLoader());  
  19.     }  
  20.     // 返回代理对象   
  21.     public Object getObject() {  
  22.         return this.serviceProxy;  
  23.     }  
  24.     // 返回代理类型   
  25.     public Class<?> getObjectType() {  
  26.         return getServiceInterface();  
  27.     }  
  28.     // 既然是服务,则是单例模式   
  29.     public boolean isSingleton() {  
  30.         return true;  
  31.     }  
  32. }   

 

产生了代理对象后,客户端会根据业务需要调用代理对象的服务方法。当调用任何方法的时候,代理机制会统一的调用到超类 HTTP 唤起器客户拦截器 (HttpInvokerClientInterceptor) 中对方法拦截器接口 (MethodInterceptor) 中的 invoke 方法的是实现。如下代码所示,

 

  1. // 当调用一个代理对象的方法,AOP代理机制会将调用信息,包括调用的方法,参数等封装成MethodInvocation对象传递给MethodInterceptor的实现里   
  2. public Object invoke(MethodInvocation methodInvocation) throws Throwable {  
  3.     // 如果正在调用toString()方法,则返回服务URL信息   
  4.     if (AopUtils.isToStringMethod(methodInvocation.getMethod())) {  
  5.         return "HTTP invoker proxy for service URL [" + getServiceUrl() + "]";  
  6.     }  
  7.     // 创建远程调用对象,远程调用对象是方法调用对象的一个简单封装   
  8.     RemoteInvocation invocation = createRemoteInvocation(methodInvocation);  
  9.     RemoteInvocationResult result = null;  
  10.     try {  
  11.         // 使用HTTP调用器请求执行器调用远程的HTTP服务,并且获得返回结果   
  12.         result = executeRequest(invocation, methodInvocation);  
  13.     }  
  14.     // 这些异常是在调用过程中产生的,例如网络连接错误,返回值解析错误等等   
  15.     catch (Throwable ex) {  
  16.         throw convertHttpInvokerAccessException(ex);  
  17.     }  
  18.       
  19.     try {  
  20.         // 远程调用结果可能包含异常信息,如果有异常发生在服务器中,则需要在客户端中重现   
  21.         return recreateRemoteInvocationResult(result);  
  22.     }  
  23.     // 这些异常是发生在服务器中的异常,异常被传回了客户端,这里需要重现异常   
  24.     catch (Throwable ex) {  
  25.         // 如果结果中是唤起目标异常,则直接抛出异常   
  26.         if (result.hasInvocationTargetException()) {  
  27.             throw ex;  
  28.         }  
  29.         // 【问题】为什么唤起目标异常不需要疯涨?   
  30.           
  31.         // 否则抛出封装的异常   
  32.         else {  
  33.             throw new RemoteInvocationFailureException("Invocation of method [" + methodInvocation.getMethod() +  
  34.                     "] failed in HTTP invoker remote service at [" + getServiceUrl() + "]", ex);  
  35.         }  
  36.     }  
  37. }  
  38. //这些异常是发生在客户端和服务器端   
  39. protected RemoteAccessException convertHttpInvokerAccessException(Throwable ex) {  
  40.     // HTTP连接错误   
  41.     if (ex instanceof ConnectException) {  
  42.         throw new RemoteConnectFailureException(  
  43.                 "Could not connect to HTTP invoker remote service at [" + getServiceUrl() + "]", ex);  
  44.     }  
  45.     // 是否有返回值对象是不可解析的类型   
  46.     else if (ex instanceof ClassNotFoundException || ex instanceof NoClassDefFoundError ||  
  47.             ex instanceof InvalidClassException) {  
  48.         throw new RemoteAccessException(  
  49.                 "Could not deserialize result from HTTP invoker remote service [" + getServiceUrl() + "]", ex);  
  50.     }  
  51.     // 其他未知调用过程中的异常   
  52.     else {  
  53.         throw new RemoteAccessException(  
  54.             "Could not access HTTP invoker remote service at [" + getServiceUrl() + "]", ex);  
  55.     }  
  56. }  
  57. public class RemoteInvocationResult implements Serializable {  
  58.     // 如果存在异常则重现异常,否则返回远程结果   
  59.     public Object recreate() throws Throwable {  
  60.         // 如果异常存在   
  61.         if (this.exception != null) {  
  62.             Throwable exToThrow = this.exception;  
  63.               
  64.             // 如果是唤起目标异常,则取得发生在方法调用时真正的异常   
  65.             if (this.exception instanceof InvocationTargetException) {  
  66.                 exToThrow = ((InvocationTargetException) this.exception).getTargetException();  
  67.             }  
  68.               
  69.             // 添加客户端异常堆栈   
  70.             RemoteInvocationUtils.fillInClientStackTraceIfPossible(exToThrow);  
  71.               
  72.             // 抛出异常   
  73.             throw exToThrow;  
  74.         }  
  75.         // 否则返回服务器端结果   
  76.         else {  
  77.             return this.value;  
  78.         }  
  79.     }  
  80. }   

 

我们看到拦截器方法除了实现对远程 HTTP 服务的调用外,还对返回结果进行了处理。如果在调用过程中产生任何连接异常,结果解析异常等,则直接翻译这些异常并且抛出。然后,有些情况下,一个调用在服务器端产生了异常,异常信息通过返回的调用结果返回给客户端,这样客户端需要解析这些异常,并且重现他们。

 

我们也理解,对远程 HTTP 服务的调用是通过 HTTP 调用器请求执行器实现的。它将远程调用序列化成对象流后,通过 HTTP 连接类的支持,写入到远程服务。当远程服务处理这个请求后,返回了远程调用结果对象,并且通过反序列化解析远程调用结果对象。如下代码所示,

 

  1. // 代理方法   
  2. protected RemoteInvocationResult executeRequest(  
  3.         RemoteInvocation invocation, MethodInvocation originalInvocation) throws Exception {  
  4.     return executeRequest(invocation);  
  5. }  
  6. protected RemoteInvocationResult executeRequest(RemoteInvocation invocation) throws Exception {  
  7.     // 调用HTTP调用器请求执行器实现远程调用的   
  8.     return getHttpInvokerRequestExecutor().executeRequest(this, invocation);  
  9. }   

 

程序分析到这里,我们理解所有远程调用的处理过程是通过 HTTP 调用器请求执行器实现的。 HTTP 调用器请求执行器并不是一个单一的实现,它是一个接口,并且有两个常用的实现,一个使用 JDK 自带的 HTTP 客户端进行通讯,而另外一个使用 Apache Commons 的 HTTP 客户端,如下类图所示,

 

图表 4 ‑ 25

 

为了使我们的分析简单明白,我们这里仅仅分析基于 JDK 自带的 HTTP 客户端进行通讯的实现。首先,我们分析一下如下抽象 HTTP 唤起器请求执行器( AbstractHttpInvokerRequestExecutor )的实现。如下代码注释,

 

  1. public final RemoteInvocationResult executeRequest(  
  2.         HttpInvokerClientConfiguration config, RemoteInvocation invocation) throws Exception {  
  3.     // 将远程调用对象序列化并且输出到字节数组输出流中   
  4.     ByteArrayOutputStream baos = getByteArrayOutputStream(invocation);  
  5.       
  6.     if (logger.isDebugEnabled()) {  
  7.         logger.debug("Sending HTTP invoker request for service at [" + config.getServiceUrl() +  
  8.                 "], with size " + baos.size());  
  9.     }  
  10.       
  11.     // 代理到其他方法处理   
  12.     return doExecuteRequest(config, baos);  
  13. }  
  14. // 抽象方法供子类实现   
  15. protected abstract RemoteInvocationResult doExecuteRequest(  
  16.         HttpInvokerClientConfiguration config, ByteArrayOutputStream baos)  
  17.         throws Exception;  
  18. protected RemoteInvocationResult readRemoteInvocationResult(InputStream is, String codebaseUrl)  
  19. throws IOException, ClassNotFoundException {  
  20.     // 从HTTP请求体的输入流创建对象输入流   
  21.     ObjectInputStream ois = createObjectInputStream(decorateInputStream(is), codebaseUrl);  
  22.     try {  
  23.         // 代理到其他方法进行读操作   
  24.       return doReadRemoteInvocationResult(ois);  
  25.     }  
  26.     finally {  
  27.       ois.close();  
  28.     }  
  29. }  
  30. // 代理方法,子类可以客户换   
  31. protected InputStream decorateInputStream(InputStream is) throws IOException {  
  32.     return is;  
  33. }  
  34. protected ObjectInputStream createObjectInputStream(InputStream is, String codebaseUrl) throws IOException {  
  35.     // 使用特殊的对象输入流,如果本地不能解析放回结果中的某个类,则试图通过网络URL配置的资源解析类   
  36.     return new CodebaseAwareObjectInputStream(is, getBeanClassLoader(), codebaseUrl);  
  37. }  
  38. protected RemoteInvocationResult doReadRemoteInvocationResult(ObjectInputStream ois)  
  39. throws IOException, ClassNotFoundException {  
  40.     // 从对象流中读对象,如果没有读到远程调用结果对象,则抛出异常,终止处理   
  41.     Object obj = ois.readObject();  
  42.     if (!(obj instanceof RemoteInvocationResult)) {  
  43.     throw new RemoteException("Deserialized object needs to be assignable to type [" +  
  44.             RemoteInvocationResult.class.getName() + "]: " + obj);  
  45.     }  
  46.       
  47.     // 返回远程调用对象   
  48.     return (RemoteInvocationResult) obj;  
  49. }   

 

如此可见,对于一个远程调用抽象 HTTP 唤起器请求执行器实现了整个流程框架,但是留下了一个抽象方法,这个方法是提供给子类使用不同的方式与 HTTP 远程服务通信的。下面我们分析简单 HTTP 唤起器请求执行器( SimpleHttpInvokerRequestExecutor )是如何通过 JDK 自带的 HTTP 客户端来完成这个任务的。如下代码所示,

 

  1. // 通过JDK自带的HTTP客户端实现基于HTTP协议的远程调用   
  2. public class SimpleHttpInvokerRequestExecutor extends AbstractHttpInvokerRequestExecutor {  
  3.       
  4.     @Override  
  5.     protected RemoteInvocationResult doExecuteRequest(  
  6.             HttpInvokerClientConfiguration config, ByteArrayOutputStream baos)  
  7.             throws IOException, ClassNotFoundException {  
  8.         // 打开远程的HTTP连接   
  9.         HttpURLConnection con = openConnection(config);  
  10.           
  11.         // 设置HTTP连接信息   
  12.         prepareConnection(con, baos.size());  
  13.           
  14.         // 把准备好的序列化的远程方法调用对象的字节流写入到HTTP请求体中   
  15.         writeRequestBody(config, con, baos);  
  16.           
  17.         // 校验HTTP响应   
  18.         validateResponse(config, con);  
  19.           
  20.         // 获得HTTP相应体的流对象   
  21.         InputStream responseBody = readResponseBody(config, con);  
  22.         // 读取远程调用结果对象并返回   
  23.         return readRemoteInvocationResult(responseBody, config.getCodebaseUrl());  
  24.     }  
  25.     protected HttpURLConnection openConnection(HttpInvokerClientConfiguration config) throws IOException {  
  26.         // 打开远程服务的URL连接   
  27.         URLConnection con = new URL(config.getServiceUrl()).openConnection();  
  28.           
  29.         // 这必须是基于HTTP协议的服务   
  30.         if (!(con instanceof HttpURLConnection)) {  
  31.             throw new IOException("Service URL [" + config.getServiceUrl() + "] is not an HTTP URL");  
  32.         }  
  33.           
  34.         return (HttpURLConnection) con;  
  35.     }  
  36.     protected void prepareConnection(HttpURLConnection con, int contentLength) throws IOException {  
  37.         // 我们需要写入远程调用的序列化对象的二进制流,所以,需要使用HTTP POST方法,并且需要输出信息到服务器   
  38.         con.setDoOutput(true);  
  39.         con.setRequestMethod(HTTP_METHOD_POST);  
  40.           
  41.         // 内容类型是application/x-java-serialized-object,长度是程调用的序列化对象的二进制流的长度   
  42.         con.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType());  
  43.         con.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength));  
  44.           
  45.         // 如果地域信息存在,则设置接收语言   
  46.         LocaleContext locale = LocaleContextHolder.getLocaleContext();  
  47.         if (locale != null) {  
  48.             con.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, StringUtils.toLanguageTag(locale.getLocale()));  
  49.         }  
  50.           
  51.         // 如果接受压缩选项,则使用压缩的HTTP通信   
  52.         if (isAcceptGzipEncoding()) {  
  53.             con.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);  
  54.         }  
  55.     }  
  56.     protected void writeRequestBody(  
  57.             HttpInvokerClientConfiguration config, HttpURLConnection con, ByteArrayOutputStream baos)  
  58.             throws IOException {  
  59.         // 远程调用的序列化对象的二进制流写到HTTP连接的输出流中   
  60.         baos.writeTo(con.getOutputStream());  
  61.     }  
  62.     protected void validateResponse(HttpInvokerClientConfiguration config, HttpURLConnection con)  
  63.             throws IOException {  
  64.         // 如果接受HTTP响应代码出错,则抛出异常终止处理,说明服务器没有开启,或者服务配置错误   
  65.         if (con.getResponseCode() >= 300) {  
  66.             throw new IOException(  
  67.                     "Did not receive successful HTTP response: status code = " + con.getResponseCode() +  
  68.                     ", status message = [" + con.getResponseMessage() + "]");  
  69.         }  
  70.     }  
  71.     protected InputStream readResponseBody(HttpInvokerClientConfiguration config, HttpURLConnection con)  
  72.             throws IOException {  
  73.         if (isGzipResponse(con)) {  
  74.             // GZIP response found - need to unzip.   
  75.             return new GZIPInputStream(con.getInputStream());  
  76.         }  
  77.         else {  
  78.             // Plain response found.   
  79.             return con.getInputStream();  
  80.         }  
  81.     }  
  82.     protected boolean isGzipResponse(HttpURLConnection con) {  
  83.         // 通过HTTP头判断是否这是一个压缩过的HTTP相应   
  84.         String encodingHeader = con.getHeaderField(HTTP_HEADER_CONTENT_ENCODING);  
  85.         return (encodingHeader != null && encodingHeader.toLowerCase().indexOf(ENCODING_GZIP) != -1);  
  86.     }  
  87. }   

 

由此可见,简单 HTTP 唤起器请求执行器通过 JDK 自带的 URL 连接类实现了远程调用所需要 HTTP 通信的流程。这个流程支持 HTTP 请求体的压缩,并且能够使用地域信息进行一定程度的客户化。

 

代码分析到这里,我们理解一个远程调用( RemoteInvocation )对象写入了 HTTP 服务中后,服务器就会返回一个远程调用结果( RemoteInvocationResult )对象。下面我们分析服务器端是如何实现这个过程的。如下类图所示,

 

图表 4 ‑ 26

 

服务器端对基于 HTTP 请求处理器流程的实现仍然是建立在 Spring Web MVC 的实现架构中的。它和基于简单控制器流程的实现和基于注解控制器流程的实现非常相似,同样有处理器映射,处理器适配器和处理器的实现,但是唯一不同的是它并没有特殊的处理器映射的实现,因为客户端是通过配置的 URL 查找和调用服务器端的服务的,所以简单基于简单控制器流程的实现中的 Bean 名 URL 处理器映射在这里可以被完全重用。如下流程图所示,

 

图表 4 ‑ 27

 

下面我们根据上图中流程的先后顺序分析它的实现。首先,派遣器 Servlet 接收到一个包含有远程调用序列化的二进制流的 HTTP 请求,它会使用配置的处理器映射查找能够处理当前 HTTP 请求的处理器。通常情况下, Bean 名 URL 处理器映射会返回配置的 HTTP 调用器服务导出器 (HttpInvokerServiceExporter) 。如下配置代码所示,

 

 

  1. <bean name="/AccountService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">  
  2.     <property name="service" ref="accountService"/>  
  3.     <property name="serviceInterface" value="example.AccountService"/>  
  4. </bean>   

 

Bean 名 URL 处理器映射会发现这个 Bean 是一个处理器 Bean, 然后使用 Bean 作为 URL 注册此处理器。客户端 HTTP 请求发送到这个 URL, 作为总控制器的派遣器 Servlet 要求 Bean 名 URL 处理器映射解析当前请求所需要的处理器,于是返回配置的 HTTP 调用器服务导出器。

 

既然 HTTP 调用器服务导出器实现了 HTTP 请求处理器接口 (HttpRequestHandler) , HTTP 请求处理器适配器 (HttpRequestHandlerAdapter) 支持这个类型的处理器,所以,调用的控制流通过 HTTP 请求处理器适配器传递给 HTTP 调用器服务导出器。如下代码注释,

 

  1. // 用于适配HTTP请求处理器的处理器适配器,主要用于实现基于HTTP的远程调用   
  2. public class HttpRequestHandlerAdapter implements HandlerAdapter {  
  3.     public boolean supports(Object handler) {  
  4.         // 支持类型任何实现了接口HttpRequestHandler的处理器   
  5.         return (handler instanceof HttpRequestHandler);  
  6.     }  
  7.     public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)  
  8.             throws Exception {  
  9.         // 传递控制给HttpRequestHandler,不需要返回值,响应是在HttpRequestHandler直接生成的   
  10.         ((HttpRequestHandler) handler).handleRequest(request, response);  
  11.         return null;  
  12.     }  
  13.     public long getLastModified(HttpServletRequest request, Object handler) {  
  14.         // 通用的实现HttpInvokerServiceExporter不支持最后修改操作   
  15.         if (handler instanceof LastModified) {  
  16.             return ((LastModified) handler).getLastModified(request);  
  17.         }  
  18.         return -1L;  
  19.     }  
  20. }   

 

程序分析到这里,我们看到包含有远程调用序列化的二进制流的 HTTP 请求传递给 HTTP 调用器服务导出器,它将从序列化的二进制流中解析远程调用对象,进而解析方法调用对象,最后使用反射调用配置的服务中相应的方法,返回结果给客户端。如下代码所示,

 

  1. // 方法没有返回值,响应是在处理请求时生成和返回给客户端的    
  2. public void handleRequest(HttpServletRequest request, HttpServletResponse response)  
  3.         throws ServletException, IOException {  
  4.     try {  
  5.         // 从请求中读取远程调用对象   
  6.         RemoteInvocation invocation = readRemoteInvocation(request);  
  7.           
  8.         // 根据远程调用对象的信息,调用配置服务的相应服务方法   
  9.         RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy());  
  10.           
  11.         // 写响应结果   
  12.         writeRemoteInvocationResult(request, response, result);  
  13.     }  
  14.     catch (ClassNotFoundException ex) {  
  15.         // 从客户端发送的二进制序列化流可能包含有不可识别的类类型,这是抛出异常终止处理   
  16.         throw new NestedServletException("Class not found during deserialization", ex);  
  17.     }  
  18. }   

 

上述方法中可以看到实现的总体流程,这个流程分为三个步骤,一个步骤是读取远程调用对象,第二个步骤是调用相关的服务方法,第三个步骤则是写入返回的结果。

 

第一个步骤,读取远程调用对象代码注释如下,

 

  1. protected RemoteInvocation readRemoteInvocation(HttpServletRequest request)  
  2.         throws IOException, ClassNotFoundException {  
  3.     // 从HTTP请求体中的流中读取远程调用对象   
  4.     return readRemoteInvocation(request, request.getInputStream());  
  5. }  
  6. protected RemoteInvocation readRemoteInvocation(HttpServletRequest request, InputStream is)  
  7.         throws IOException, ClassNotFoundException {  
  8.     // 从简单的流构造对象流   
  9.     ObjectInputStream ois = createObjectInputStream(decorateInputStream(request, is));  
  10.     try {  
  11.         // 从对象流中读取远程调用对象   
  12.         return doReadRemoteInvocation(ois);  
  13.     }  
  14.     finally {  
  15.         ois.close();  
  16.     }  
  17. }  
  18. protected InputStream decorateInputStream(HttpServletRequest request, InputStream is) throws IOException {  
  19.     // 占位符方法,仅仅返回HTTP请求体中的流对象   
  20.     return is;  
  21. }  
  22. protected ObjectInputStream createObjectInputStream(InputStream is) throws IOException {  
  23.     // 特殊的对象输入流,可以配置客户化的类加载器,如果某些类不存在,可以视图通过一个配置的URL加载此类   
  24.     return new CodebaseAwareObjectInputStream(is, getBeanClassLoader(), null);  
  25. }  
  26. protected RemoteInvocation doReadRemoteInvocation(ObjectInputStream ois)  
  27. throws IOException, ClassNotFoundException {  
  28.     // 读取HTTP请求体的序列化的对象   
  29.     Object obj = ois.readObject();  
  30.       
  31.     // 如果不是远程调用的序列化流,则终止异常   
  32.     if (!(obj instanceof RemoteInvocation)) {  
  33.         throw new RemoteException("Deserialized object needs to be assignable to type [" +  
  34.                 RemoteInvocation.class.getName() + "]: " + obj);  
  35.     }  
  36.       
  37.     return (RemoteInvocation) obj;  
  38. }   

 

第二个步骤,调用相关的服务方法代码注释如下所示,

 

  1. protected RemoteInvocationResult invokeAndCreateResult(RemoteInvocation invocation, Object targetObject) {  
  2.     try {  
  3.         // 事实上调用服务方法   
  4.         Object value = invoke(invocation, targetObject);  
  5.           
  6.         // 返回正确的远程结果   
  7.         return new RemoteInvocationResult(value);  
  8.     }  
  9.     catch (Throwable ex) {  
  10.         // 调用过程中如果有异常发生,则返回带有异常的远程调用结果,客户端将会重现这个异常   
  11.         return new RemoteInvocationResult(ex);  
  12.     }  
  13. }  
  14. protected Object invoke(RemoteInvocation invocation, Object targetObject)  
  15. throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {  
  16.     if (logger.isTraceEnabled()) {  
  17.         logger.trace("Executing " + invocation);  
  18.     }  
  19.     try {  
  20.         // 使用远程调用执行器执行服务方法,抛出产生的任何异常   
  21.         return getRemoteInvocationExecutor().invoke(invocation, targetObject);  
  22.     }  
  23.     catch (NoSuchMethodException ex) {  
  24.         if (logger.isDebugEnabled()) {  
  25.             logger.warn("Could not find target method for " + invocation, ex);  
  26.         }  
  27.         throw ex;  
  28.     }  
  29.     catch (IllegalAccessException ex) {  
  30.         if (logger.isDebugEnabled()) {  
  31.             logger.warn("Could not access target method for " + invocation, ex);  
  32.         }  
  33.         throw ex;  
  34.     }  
  35.     catch (InvocationTargetException ex) {  
  36.         if (logger.isDebugEnabled()) {  
  37.             logger.debug("Target method failed for " + invocation, ex.getTargetException());  
  38.         }  
  39.         throw ex;  
  40.     }  
  41. }  
  42. //远程调用执行器只有一个缺省的实现,缺省的实现简单的调用远程调用对象的默认实现   
  43. public class DefaultRemoteInvocationExecutor implements RemoteInvocationExecutor {  
  44.     public Object invoke(RemoteInvocation invocation, Object targetObject)  
  45.             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException{  
  46.         // 校验远程调用对象和配置的服务对象存在   
  47.         Assert.notNull(invocation, "RemoteInvocation must not be null");  
  48.         Assert.notNull(targetObject, "Target object must not be null");  
  49.           
  50.         // 调用远程调用的默认实现   
  51.         return invocation.invoke(targetObject);  
  52.     }  
  53. }  
  54. public class RemoteInvocation implements Serializable {  
  55.     public Object invoke(Object targetObject) throws NoSuchMethodException,  
  56.             IllegalAccessException, InvocationTargetException {  
  57.         // 通过远程调用对象包含的方法名和参数类型找到服务对象的方法   
  58.         Method method = targetObject.getClass().getMethod(this.methodName,  
  59.                 this.parameterTypes);  
  60.         // 调用找到的方法   
  61.         return method.invoke(targetObject, this.arguments);  
  62.     }  
  63. }   

 

第三个步骤,写入返回的结果的代码注释如下所示,

 

  1. protected void writeRemoteInvocationResult(  
  2.         HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result)  
  3.         throws IOException {  
  4.     // 设置内容类型为application/x-java-serialized-object   
  5.     response.setContentType(getContentType());  
  6.       
  7.     // 写远程调用结果到响应的输出流   
  8.     writeRemoteInvocationResult(request, response, result, response.getOutputStream());  
  9. }  
  10. protected void writeRemoteInvocationResult(  
  11.         HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result, OutputStream os)  
  12.         throws IOException {  
  13.     // 创建对象输出流   
  14.     ObjectOutputStream oos = createObjectOutputStream(decorateOutputStream(request, response, os));  
  15.     try {  
  16.         // 将远程调用结果对象写入到代表响应的对象输出流   
  17.         doWriteRemoteInvocationResult(result, oos);  
  18.         //    
  19.         将缓存刷新到HTTP响应体中  
  20.         oos.flush();  
  21.     }  
  22.     finally {  
  23.         oos.close();  
  24.     }  
  25. }  
  26. protected ObjectOutputStream createObjectOutputStream(OutputStream os) throws IOException {  
  27.     // 创建简单的对象输出流,用于序列化远程调用结果对象   
  28.     return new ObjectOutputStream(os);  
  29. }  
  30. protected void doWriteRemoteInvocationResult(RemoteInvocationResult result, ObjectOutputStream oos)  
  31. throws IOException {  
  32.     // 既然远程调用结果对象是可序列化的,直接写远程调用结果对象到对象流   
  33.     oos.writeObject(result);  
  34. }   

 

如上分析,我们知道服务端的实现是讲客户端传递过来的远程调用的序列化对象进行反序列化,根据远程调用对象信息调用业务逻辑方法,最后同样以序列化的方法将调用结果传递回客户端。

 

事实上,还有另外一种配置方法配置基于 HTTP 请求处理器流程的实现方式。这种方法不需要任何的处理器映射和处理器适配器的实现,而是使用特殊的 HTTP 请求处理器 Servlet ( HttpRequestHandlerServlet )。这个 Servlet 会将 HTTP 请求直接发送给相应的 HTTP 调用器服务导出器进行处理。如下图所示,

 

图表 4 ‑ 28

 

如下代码所示,

 

  1. public class HttpRequestHandlerServlet extends HttpServlet {  
  2.     private HttpRequestHandler target;  
  3.     @Override  
  4.     public void init() throws ServletException {  
  5.         // 取得根Web应用程序环境   
  6.         WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());  
  7.           
  8.         // 取得和此Servlet具有同名的Bean,这个Bean必须是HttpRequestHandler接口的实现   
  9.         this.target = (HttpRequestHandler) wac.getBean(getServletName(), HttpRequestHandler.class);  
  10.     }  
  11.     @Override  
  12.     protected void service(HttpServletRequest request, HttpServletResponse response)  
  13.             throws ServletException, IOException {  
  14.         // 设置地域信息   
  15.         LocaleContextHolder.setLocale(request.getLocale());  
  16.         try {  
  17.             // 讲控制流传递给HttpRequestHandler   
  18.             this.target.handleRequest(request, response);  
  19.         }  
  20.         // 既然我们重写了service方法,那么所有的HTTP方法的请求都可能会发送到这里,所以HttpRequestHandler的实现需要检查是否当前请求使用了支持的HTTP方法   
  21.         catch (HttpRequestMethodNotSupportedException ex) {  
  22.             String[] supportedMethods = ((HttpRequestMethodNotSupportedException) ex).getSupportedMethods();  
  23.             if (supportedMethods != null) {  
  24.                 // 如果异常中保存了支持的HTTP方法信息   
  25.                 response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));  
  26.             }  
  27.             // 发送方法禁止错误状态   
  28.             response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());  
  29.         }  
  30.         finally {  
  31.             LocaleContextHolder.resetLocaleContext();  
  32.         }  
  33.     }  
  34. }   

 

根据上面的这个简单 Servlet 的实现,我们可以这样配置我们的远程调用导出器。如下代码所示,

 

跟环境

 

 

  1. <bean name="accountExporter" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">  
  2.     <property name="service" ref="accountService"/>  
  3.     <property name="serviceInterface" value="example.AccountService"/>  
  4. </bean>   

 

web.xml

 

 

  1. <servlet>  
  2.     <servlet-name>accountExporter</servlet-name>  
  3.     <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>  
  4. </servlet>  
  5. <servlet-mapping>  
  6.     <servlet-name>accountExporter</servlet-name>  
  7.     <url-pattern>/remoting/AccountService</url-pattern>  
  8. </servlet-mapping>   

 

我们可以看到这种实现方法涉及组件会更少,不需要处理器映射和处理器适配器的参与,直接实现了 Servlet 到处理器适配器的调用,相对于第一种方法而言可以称为是一个捷径。但是它需要单独配置一个 Servlet ,除此之外, HTTP 请求处理器 Servlet 仅仅实现了 HTTP Servlet, 它并不拥有专用的子环境,所以需要在根环境声明服务导出 Bean 。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值