Spring使用Hessian實現遠程調用

1.Spring中除了提供HTTP調用器方式的遠程調用,還對第三方的遠程調用實現提供了支持,其中提供了對Hessian的支持。html

Hessian是由Caocho公司發佈的一個輕量級的二進制協議遠程調用實現方案,Hessian也是基於HTTP協議的,其工做原理以下:java

(1).客戶端:spring

a.發送遠程調用請求:服務器

客戶端程序—>發送遠程調用請求—>Hessian客戶端攔截器—>封裝遠程調用請求—>Hessian代理—>經過HTTP協議發送遠程請求代理到服務端。app

b.接收遠程調用響應:框架

遠程調用結果—>HTTP響應—>客戶端。ide

(1).服務端:源碼分析

a.接收遠程調用請求:ui

遠程調用HTTP請求—>HessianServiceExporter接收請求—>HessianExporter將遠程調用對象封裝爲HessianSkeleton框架—HessianSkeleton處理遠程調用請求this

b.返回遠程調用響應:

HessianSkeleton封裝遠程調用處理結果>HTTP響應—>客戶端。

本文章經過分析SpringHessian支持的相關源碼,瞭解SpringHessian支持的具體實現。

2.Hessian的客戶端配置:

Hessian的客戶端須要作相似以下的配置:

[xhtml] view plaincopy

  1. <bean id=」hessianProxy」 class=」org.springframework.remoting.caucho.HessianProxyFactoryBean」>  

  2. <property name=」serviceUrl」>  

  3. <value>http://hostAddress:8080/serviceUrl</value>  

  4. </property>  

  5. <property name=」serviceInterface」>  

  6. <value>遠程調用服務接口</value>  

  7. ]</property>  

  8. </bean>  

HTTP調用器的配置相似,都須要配置遠程調用請求的url,這個url要和服務端的url一致,Spring經過DispatcherServlet找到服務端對於的請求url

HessianProxyFactoryBeanSpring中管理Hessian客戶端的IoC容器,主要負責產生服務端遠程調用代理和對客戶端遠程調用的攔截器設置。

3.HessianProxyFactoryBean

HessianProxyFactoryBean生成遠程調用代理和客戶端遠程調用攔截器設置,其源碼以下:

[java] view plaincopy

  1. public class HessianProxyFactoryBean extends HessianClientInterceptor implements FactoryBean<Object> {  

  2.     //遠程調用代理對象  

  3.     private Object serviceProxy;  

  4.     //Spring IoC容器依賴注入完成後的回調方法  

  5.     public void afterPropertiesSet() {  

  6.         //首先調用父類HessianClientInterceptor的回調方法  

  7.         super.afterPropertiesSet();  

  8. //建立遠程調用代理對象並設置攔截器,注意這個this參數,由於//HessianProxyFactoryBean繼承HessianClientInterceptor,所以其自己也  

  9. //是Hassien客戶端攔截器  

  10.         this.serviceProxy = new ProxyFactory(getServiceInterface(), this).getProxy(getBeanClassLoader());  

  11.     }  

  12.     //Spring IoC容器的接口FactoryBean產生對象的方法,客戶端經過該方法獲取被管  

  13. //理的遠程調用代理  

  14.     public Object getObject() {  

  15.         return this.serviceProxy;  

  16.     }  

  17.     //獲取對象的類型  

  18.     public Class<?> getObjectType() {  

  19.         return getServiceInterface();  

  20.     }  

  21.     //對象是不是單態類型,Spring默認管理的對象都是單態模式  

  22.     public boolean isSingleton() {  

  23.         return true;  

  24.     }  

  25. }  

HessianProxyFactoryBean最核心的功能就是在IoC容器回調方法中產生遠程調用代理對象,在產生遠程調用代理對象時,將代理對象的攔截器設置爲其父類HessianClientInterceptor

4.HessianClientInterceptor攔截客戶端的遠程調用請求:

HessianClientInterceptor對客戶端的遠程調用進行攔截,爲客戶端的遠程調用建立Hessian代理,經過Hessian代理調用服務端遠程調用對象,其源碼以下:

[java] view plaincopy

  1. public class HessianClientInterceptor extends UrlBasedRemoteAccessor implements MethodInterceptor {  

  2.     //建立Hessiann代理工廠  

  3.     private HessianProxyFactory proxyFactory = new HessianProxyFactory();  

  4.     //Hessian代理  

  5.     private Object hessianProxy;  

  6. //設置Hessian代理工廠  

  7.     public void setProxyFactory(HessianProxyFactory proxyFactory) {  

  8.         this.proxyFactory = (proxyFactory != null ? proxyFactory : new HessianProxyFactory());  

  9.     }  

  10.     //設置Hessian序列化工廠  

  11.     public void setSerializerFactory(SerializerFactory serializerFactory) {  

  12.         this.proxyFactory.setSerializerFactory(serializerFactory);  

  13.     }  

  14.     //設置Hessian是否發送java集合類型對象  

  15.     public void setSendCollectionType(boolean sendCollectionType) {  

  16.     this.proxyFactory.getSerializerFactory().setSendCollectionType(sendCollectionType);  

  17.     }  

  18.     //設置遠程調用時是否重載方法  

  19.     public void setOverloadEnabled(boolean overloadEnabled) {  

  20.         this.proxyFactory.setOverloadEnabled(overloadEnabled);  

  21.     }  

  22.     //設置遠程調用用戶名  

  23.     public void setUsername(String username) {  

  24.         this.proxyFactory.setUser(username);  

  25.     }  

  26.     //設置遠程調用密碼  

  27.     public void setPassword(String password) {  

  28.         this.proxyFactory.setPassword(password);  

  29.     }  

  30.     //設置是否使用Hessian的Debug調試模式  

  31.     public void setDebug(boolean debug) {  

  32.         this.proxyFactory.setDebug(debug);  

  33.     }  

  34.     //設置是否使用chunked端口發送Hessian請求  

  35.     public void setChunkedPost(boolean chunkedPost) {  

  36.         this.proxyFactory.setChunkedPost(chunkedPost);  

  37.     }  

  38.     //設置Hessian等待響應的超時時長  

  39.     public void setReadTimeout(long timeout) {  

  40.         this.proxyFactory.setReadTimeout(timeout);  

  41.     }  

  42.     //設置是否使用Hessain版本2協議解析請求和響應  

  43.     public void setHessian2(boolean hessian2) {  

  44.         this.proxyFactory.setHessian2Request(hessian2);  

  45.         this.proxyFactory.setHessian2Reply(hessian2);  

  46.     }  

  47.     //設置是否使用Hessian版本2協議解析請求  

  48.     public void setHessian2Request(boolean hessian2) {  

  49.         this.proxyFactory.setHessian2Request(hessian2);  

  50.     }  

  51.     //設置是否使用Hessian版本2協議解析響應  

  52.     public void setHessian2Reply(boolean hessian2) {  

  53.         this.proxyFactory.setHessian2Reply(hessian2);  

  54.     }  

  55. //子類HessianProxyFactoryBean的回調方法調用此回調方法  

  56.     public void afterPropertiesSet() {  

  57.         //調用其父類UrlBasedRemoteAccessor的回調方法獲取客戶端配置的請求url  

  58.         super.afterPropertiesSet();  

  59.         //初始化Hessian代理  

  60.         prepare();  

  61.     }  

  62.     //初始化Hessian代理  

  63.     public void prepare() throws RemoteLookupFailureException {  

  64.         try {  

  65.             //建立Hessian代理  

  66.             this.hessianProxy = createHessianProxy(this.proxyFactory);  

  67.         }  

  68.         catch (MalformedURLException ex) {  

  69.             throw new RemoteLookupFailureException("Service URL [" + getServiceUrl() + "] is invalid", ex);  

  70.         }  

  71.     }  

  72.     //建立Hessian代理  

  73.     protected Object createHessianProxy(HessianProxyFactory proxyFactory) throws MalformedURLException {  

  74.         Assert.notNull(getServiceInterface(), "'serviceInterface' is required");  

  75.         //使用Hessian代理工廠建立Hessian代理  

  76.         return proxyFactory.create(getServiceInterface(), getServiceUrl());  

  77.     }  

  78.     //攔截器客戶端請求的方法  

  79.     public Object invoke(MethodInvocation invocation) throws Throwable {  

  80.         if (this.hessianProxy == null) {  

  81.             throw new IllegalStateException("HessianClientInterceptor is not properly initialized - " +  

  82.                     "invoke 'prepare' before attempting any operations");  

  83.         }  

  84.         //獲取當前環境中線程類加載器  

  85.         ClassLoader originalClassLoader = overrideThreadContextClassLoader();  

  86.         try {  

  87.         //調用Hessian代理的方法,是Hessian遠程調用的入口方法,使用JDK反射機制  

  88.             return invocation.getMethod().invoke(this.hessianProxy, invocation.getArguments());  

  89.         }  

  90.         //處理Hessian遠程調用中的異常  

  91.         catch (InvocationTargetException ex) {  

  92.             Throwable targetEx = ex.getTargetException();  

  93.             if (targetEx instanceof InvocationTargetException) {  

  94.                 targetEx = ((InvocationTargetException) targetEx).getTargetException();  

  95.             }  

  96.             if (targetEx instanceof HessianConnectionException) {  

  97.                 throw convertHessianAccessException(targetEx);  

  98.             }  

  99.             else if (targetEx instanceof HessianException || targetEx instanceof HessianRuntimeException) {  

  100.                 Throwable cause = targetEx.getCause();  

  101.                 throw convertHessianAccessException(cause != null ? cause : targetEx);  

  102.             }  

  103.             else if (targetEx instanceof UndeclaredThrowableException) {  

  104.                 UndeclaredThrowableException utex = (UndeclaredThrowableException) targetEx;  

  105.                 throw convertHessianAccessException(utex.getUndeclaredThrowable());  

  106.             }  

  107.             else {  

  108.                 throw targetEx;  

  109.             }  

  110.         }  

  111.         catch (Throwable ex) {  

  112.             throw new RemoteProxyFailureException(  

  113.                     "Failed to invoke Hessian proxy for remote service [" + getServiceUrl() + "]", ex);  

  114.         }  

  115.         //重置類加載器  

  116.         finally {  

  117.             resetThreadContextClassLoader(originalClassLoader);  

  118.         }  

  119.     }  

  120.     //將Hessian異常轉換爲Spring遠程調用異常  

  121.     protected RemoteAccessException convertHessianAccessException(Throwable ex) {  

  122.         if (ex instanceof HessianConnectionException || ex instanceof ConnectException) {  

  123.             return new RemoteConnectFailureException(  

  124.                     "Cannot connect to Hessian remote service at [" + getServiceUrl() + "]", ex);  

  125.         }  

  126.         else {  

  127.             return new RemoteAccessException(  

  128.                 "Cannot access Hessian remote service at [" + getServiceUrl() + "]", ex);  

  129.         }  

  130.     }  

  131. }  

經過上面對HessianClientInterceptor的源碼分析,咱們能夠看到Hessian客戶端攔截器提供的最重要的方法是對遠程調用攔截的方法invoke,在該方法中使用JDK的反射機制調用Hessian代理對象的指定方法。而Hessian代理是由Hessain代理器工廠HessianProxyFactory產生的,這個Hessian代理器工廠是有Hessian提供的。

5.Hessian服務器端配置:

Hessian的服務端須要進行相似以下的配置:

[xhtml] view plaincopy

  1. <bean id=」/serviceUrl」 class=」org.springframework.remoting.caucho.HessianServiceExporter」>  

  2. <property name=」service」>  

  3. <ref bean=」service」/>  

  4. </property>  

  5. <property name=」serviceInterface」>  

  6. <value>遠程服務接口</value>  

  7. </property>  

  8. </bean>  

SpringHessianServiceExporter把遠程調用服務整合到Spring MVC框架中,經過DispatcherServlet將客戶端請求轉發到服務器端相應的請求url遠程對象上。

注意:serviceUrl要和客戶端serviceUrl中配置的相同,service便是服務端提供服務的遠程對象。

6.HessianServiceExporter處理Hessian遠程調用請求

HessianServiceExporter接收客戶端的遠程調用請求,並調用HessianExporter具體處理遠程調用,而且遠程調用結果封裝到HTTP響應中返回,源碼以下:

[java] view plaincopy

  1. public class HessianServiceExporter extends HessianExporter implements HttpRequestHandler {  

  2.     //處理Hessian請求,並將處理結果封裝爲Hessian響應返回  

  3.     public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

  4.         //Hessian只支持HTTP的POST方法  

  5.         if (!"POST".equals(request.getMethod())) {  

  6.             throw new HttpRequestMethodNotSupportedException(request.getMethod(),  

  7.                     new String[] {"POST"}, "HessianServiceExporter only supports POST requests");  

  8.         }  

  9.         //設置Hessian響應內容類型爲:application/x-hessian  

  10.         response.setContentType(CONTENT_TYPE_HESSIAN);  

  11.         try {  

  12.           //HessianExporter真正處理Hessian請求和封裝Hessian響應的方法  

  13.           invoke(request.getInputStream(), response.getOutputStream());  

  14.         }  

  15.         catch (Throwable ex) {  

  16.           throw new NestedServletException("Hessian skeleton invocation failed", ex);  

  17.         }  

  18.     }  

  19. }  

7.HessianExporter處理Hessian請求並將結果封裝爲HTTP響應:

[java] view plaincopy

  1. public class HessianExporter extends RemoteExporter implements InitializingBean {  

  2.     //Hessian HTTP響應內容類型  

  3.     public static final String CONTENT_TYPE_HESSIAN = "application/x-hessian";  

  4.     //Hessian序列化工廠  

  5.     private SerializerFactory serializerFactory = new SerializerFactory();  

  6.     //Hessian Debug日誌  

  7.     private Log debugLogger;  

  8.     //Hessian服務端框架  

  9.     private HessianSkeleton skeleton;  

  10. //設置Hessian序列化工廠  

  11.     public void setSerializerFactory(SerializerFactory serializerFactory) {  

  12.         this.serializerFactory = (serializerFactory != null ? serializerFactory : new SerializerFactory());  

  13.     }  

  14.     //設置序列化集合發送java集合類型  

  15.     public void setSendCollectionType(boolean sendCollectionType) {  

  16.     this.serializerFactory.setSendCollectionType(sendCollectionType);  

  17.     }  

  18.     //設置Hessian調試模式  

  19.     public void setDebug(boolean debug) {  

  20.         this.debugLogger = (debug ? logger : null);  

  21.     }  

  22.     //回調方法  

  23.     public void afterPropertiesSet() {  

  24.         prepare();  

  25.     }  

  26.     //初始化Hessian服務框架  

  27.     public void prepare() {  

  28.         //這裏調用父類RemoteExporter的方法檢查服務提供類、服務接口  

  29.         checkService();  

  30.         checkServiceInterface();  

  31.         //建立遠程服務類的Hessian框架  

  32.         this.skeleton = new HessianSkeleton(getProxyForService(), getServiceInterface());  

  33.     }  

  34. //遠程調用處理入口  

  35.     public void invoke(InputStream inputStream, OutputStream outputStream) throws Throwable {  

  36.         Assert.notNull(this.skeleton, "Hessian exporter has not been initialized");  

  37.         doInvoke(this.skeleton, inputStream, outputStream);  

  38.     }  

  39.     //遠程調用處理方法  

  40.     protected void doInvoke(HessianSkeleton skeleton, InputStream inputStream, OutputStream outputStream)  

  41.             throws Throwable {  

  42.         //獲取類加載器  

  43.         ClassLoader originalClassLoader = overrideThreadContextClassLoader();  

  44.         try {  

  45.             InputStream isToUse = inputStream;  

  46.             OutputStream osToUse = outputStream;  

  47.             //設置Hessian調試日誌  

  48.             if (this.debugLogger != null && this.debugLogger.isDebugEnabled()) {  

  49.                 PrintWriter debugWriter = new PrintWriter(new CommonsLogWriter(this.debugLogger));  

  50.                 HessianDebugInputStream dis = new HessianDebugInputStream(inputStream, debugWriter);  

  51.                 dis.startTop2();  

  52.                 HessianDebugOutputStream dos = new HessianDebugOutputStream(outputStream, debugWriter);  

  53.                 dos.startTop2();  

  54.                 isToUse = dis;  

  55.                 osToUse = dos;  

  56.             }  

  57.             if (!isToUse.markSupported()) {  

  58.                 isToUse = new BufferedInputStream(isToUse);  

  59.                 isToUse.mark(1);  

  60.             }  

  61.             int code = isToUse.read();  

  62.             int major;  

  63.             int minor;  

  64.             AbstractHessianInput in;  

  65.             AbstractHessianOutput out;  

  66.             //根據客戶端不一樣的Hessian版本,設置不一樣的Hessian抽象輸入/輸出  

  67.             //Hessian2.0  

  68.             if (code == 'H') {  

  69.                 major = isToUse.read();  

  70.                 minor = isToUse.read();  

  71.                 if (major != 0x02) {  

  72.                     throw new IOException("Version " + major + "." + minor + " is not understood");  

  73.                 }  

  74.                 in = new Hessian2Input(isToUse);  

  75.                 out = new Hessian2Output(osToUse);  

  76.                 in.readCall();  

  77.             }  

  78.             //Hessian2.0  

  79.             else if (code == 'C') {  

  80.                 isToUse.reset();  

  81.                 in = new Hessian2Input(isToUse);  

  82.                 out = new Hessian2Output(osToUse);  

  83.                 in.readCall();  

  84.             }  

  85.             //Hessian1.0  

  86.             else if (code == 'c') {  

  87.                 major = isToUse.read();  

  88.                 minor = isToUse.read();  

  89.                 in = new HessianInput(isToUse);  

  90.                 if (major >= 2) {  

  91.                     out = new Hessian2Output(osToUse);  

  92.                 }  

  93.                 else {  

  94.                     out = new HessianOutput(osToUse);  

  95.                 }  

  96.             }  

  97.             else {  

  98.                 throw new IOException("Expected 'H'/'C' (Hessian 2.0) or 'c' (Hessian 1.0) in hessian input at " + code);  

  99.             }  

  100.             //設置Hessian序列化工廠  

  101.             if (this.serializerFactory != null) {  

  102.                 in.setSerializerFactory(this.serializerFactory);  

  103.                 out.setSerializerFactory(this.serializerFactory);  

  104.             }  

  105.             try {  

  106.                 //經過服務端遠程對象的Hessian框架處理遠程調用  

  107.                 skeleton.invoke(in, out);  

  108.             }  

  109.             finally {  

  110.                 try {  

  111.                     in.close();  

  112.                     isToUse.close();  

  113.                 }  

  114.                 catch (IOException ex) {  

  115.                 }  

  116.                 try {  

  117.                     out.close();  

  118.                     osToUse.close();  

  119.                 }  

  120.                 catch (IOException ex) {  

  121.                 }  

  122.             }  

  123.         }  

  124.         //重置類加載器  

  125.         finally {  

  126.             resetThreadContextClassLoader(originalClassLoader);  

  127.         }  

  128.     }  

  129. }  

經過上面對HessianExporter源碼分析,咱們看到真正進行遠程調用處理的是由Hessian提供的服務端HessianSkeleton

相關文章
相關標籤/搜索