Spring框架学习[Spring HTTP调用器实现远程调用](七)

2014-11-24 03:00:37 · 作者: · 浏览: 8
ody(HttpInvokerClientConfiguration config, HttpURLConnection con) throws IOException { //如果响应信息是Gzip压缩的,则需要先解压 if (isGzipResponse(con)) { return new GZIPInputStream(con.getInputStream()); } //正常的HTTP响应 else { return con.getInputStream(); } } //是否是Gzip格式压缩 protected boolean isGzipResponse(HttpURLConnection con) { //获取HTTP响应头信息中的压缩方式 String encodingHeader = con.getHeaderField(HTTP_HEADER_CONTENT_ENCODING); return (encodingHeader != null && encodingHeader.toLowerCase().indexOf(ENCODING_GZIP) != -1); } }

通过对SimpleHttpInvokerRequestExecutor的分析,我们看到,HTTP调用请求执行器的处理逻辑是:首先,打开指定URL的HTTP连接,设置连接属性。其次,将封装请求的RemoteInvocation对象序列化到请求体中,请HTTP请求发送到服务器端。最后,从服务器端的HTTP响应中读取输入流,并将响应结果转换成RemoteInvocationResult。

将远程调用的HTTP响应转换为RemoteInvocationResult是由AbstractHttpInvokerRequestExecutor的readRemoteInvocationResult方法实现,下面我们将分析其将HTTP响应结果转换成RemoteInvocationResult的实现。

6.AbstractHttpInvokerRequestExecutor其将HTTP响应结果转换成RemoteInvocationResult:

AbstractHttpInvokerRequestExecutor中处理远程调用结果,并HTTP响应转换为RemoteInvocationResult的主要方法如下:

[java] view plaincopyprint
  1. //从HTTP响应中读取远程调用结果入口方法 protected RemoteInvocationResult readRemoteInvocationResult(InputStream is, String codebaseUrl)
  2. throws IOException, ClassNotFoundException { //根据给定的输入流和类创建对象输入流
  3. ObjectInputStream ois = createObjectInputStream(decorateInputStream(is), codebaseUrl); try {
  4. //从对象输入流中读取远程调用结果 return doReadRemoteInvocationResult(ois);
  5. } finally {
  6. ois.close(); }
  7. } //从对象输入流中读取远程调用结果
  8. protected RemoteInvocationResult doReadRemoteInvocationResult(ObjectInputStream ois) throws IOException, ClassNotFoundException {
  9. //获取对象输入流中的对象 Object obj = ois.readObject();
  10. if (!(obj instanceof RemoteInvocationResult)) { throw new RemoteException("Deserialized object needs to be assignable to type [" +
  11. RemoteInvocationResult.class.getName() + "]: " + obj); }
  12. //将获取到的对象封装为RemoteInvocationResult return (RemoteInvocationResult) obj;
  13. }

    7.HTTP调用器的服务器端配置:

    和HTTP调用器客户端类似,服务器端也需要进行如下的配置:

    [xhtml] view plaincopyprint
    1. 远程调用服务接口全路径
    2. 通过对服务器端配置的例子,我们可以看出,真正处理远程调用的服务器端实现是由service属性中指定的服务器端bean提供的,HttpInvokerServiceExporter将远程调用服务接口和服务实现类进行封装,主要提HTTP协议封装和java对象序列化功能。

      Spring的HttpInvokerServiceExporter是与Spring的MVC结合在一起的,它本质上是Spring M