Spring HttpInvoke實現和效率提高


Spring HttpInvoke,一種較爲經常使用的、基於Spring架構的服務器之間的遠程調用實現,能夠說是輕量級的RMI。 
最初,咱們使用Spring HttpInvoke同步配置數據,刷新多個服務器上的緩存,固然若是用分佈式緩存是否是更好 ! 
使用Spring HttpInvoke,你能夠調用遠程接口,進行數據交互、業務邏輯操做等等。 
廢話不說了,上代碼! 
用戶操做接口: 
Java代碼  
  1. /** 
  2.  * @author <a href="mailto:zlex.dongliang@gmail.com">樑棟</a> 
  3.  * @since 1.0 
  4.  */  
  5. public interface UserService {  
  6.   
  7.     /** 
  8.      * 得到用戶 
  9.      *  
  10.      * @param username 
  11.      *            用戶名 
  12.      * @return 
  13.      */  
  14.     User getUser(String username);  
  15. }  

用戶類,注意實現Serializable接口,這是執行遠程調用傳遞數據對象的第一要求——數據對象必須實現Serializable接口,由於,要執行序列化/反序列化操做! 
Java代碼  
  1. /** 
  2.  * @author <a href="mailto:zlex.dongliang@gmail.com">樑棟</a> 
  3.  * @since 1.0 
  4.  */  
  5. public class User implements Serializable {  
  6.   
  7.     private static final long serialVersionUID = 5590768569302443813L;  
  8.     private String username;  
  9.     private Date birthday;  
  10.   
  11.     /** 
  12.      * @param username 
  13.      * @param birthday 
  14.      */  
  15.     public User(String username, Date birthday) {  
  16.         this.username = username;  
  17.         this.birthday = birthday;  
  18.     }  
  19.        // 省略  
  20.     /* 
  21.      * (non-Javadoc) 
  22.      *  
  23.      * @see java.lang.Object#toString() 
  24.      */  
  25.     @Override  
  26.     public String toString() {  
  27.         return String.format("%s\t%s\t", username, birthday);  
  28.     }  
  29. }  

覆蓋toString()方法,輸出用戶信息! 
再看UserServiceImpl實現: 
Java代碼  
  1. /** 
  2.  * @author <a href="mailto:zlex.dongliang@gmail.com">樑棟</a> 
  3.  * @since 1.0 
  4.  */  
  5. public class UserServiceImpl implements UserService {  
  6.     private Logger logger = Logger.getLogger(UserServiceImpl.class);  
  7.   
  8.     /* 
  9.      * (non-Javadoc) 
  10.      *  
  11.      * @see 
  12.      * org.zlex.spring.httpinvoke.service.UserService#getUser(java.lang.String) 
  13.      */  
  14.     @Override  
  15.     public User getUser(String username) {  
  16.         if (logger.isDebugEnabled()) {  
  17.             logger.debug("username:[" + username + "]");  
  18.         }  
  19.         User user = new User(username, new Date());  
  20.         if (logger.isDebugEnabled()) {  
  21.             logger.debug("user:[" + user + "]");  
  22.         }  
  23.         return user;  
  24.     }  
  25.   
  26. }  

只把用戶信息打出來便可說明調用效果! 
看applicationContext.xml 
Xml代碼  
  1. <bean  
  2.     id="userService"  
  3. class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">  
  4.     <property  
  5.         name="service">  
  6.         <bean  
  7. class="org.zlex.spring.httpinvoke.service.impl.UserServiceImpl" />  
  8.     </property>  
  9.     <property  
  10.         name="serviceInterface"  
  11.         value="org.zlex.spring.httpinvoke.service.UserService" />  
  12. </bean>  

咱們要把userService暴露出去,這樣外部就能夠經過http接口調用這個接口的實現了。 
說說HttpInvokerServiceExporter,這個類用來在服務器端包裝須要暴露的接口。 
熟悉service,定義具體的實現類! 
Xml代碼  
  1. <property  
  2.     name="service">  
  3.     <bean  
  4. lass="org.zlex.spring.httpinvoke.service.impl.UserServiceImpl" />  
  5. </property>  

熟悉serviceInterface指向須要暴露的接口,注意使用value標註接口名稱! 
Xml代碼 
  1. <property  
  2.     name="serviceInterface"  
  3.     value="org.zlex.spring.httpinvoke.service.UserService" />  

最後再看service-servlet.xml配置 
Xml代碼  
  1. <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">  
  2.     <property  
  3.         name="urlMap">  
  4.         <map>  
  5.             <entry  
  6.                 key="userTest"  
  7.                 value-ref="userService" />  
  8.         </map>  
  9.     </property>  
  10. </bean>  

直接將請求指向剛纔配置的userService 
如今咱們之間訪問一下http://localhost:8080/spring/service/ 
 
這就說明,服務器端配置已經成功了!若是在日誌中頻繁獲得這種異常,那極可能服務器被惡意訪問了! 
再看客戶端實現: 
Java代碼  
  1. /** 
  2.  * @author <a href="mailto:zlex.dongliang@gmail.com">樑棟</a> 
  3.  * @since 1.0 
  4.  */  
  5. public class UserServiceTest {  
  6.     private Logger logger = Logger.getLogger(UserServiceTest.class);  
  7.     private ApplicationContext context;  
  8.   
  9.     private UserService userService;  
  10.   
  11.     @Before  
  12.     public void initialize() {  
  13.         context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  14.         userService = (UserService) context.getBean("userService");  
  15.     }  
  16.   
  17.     @Test  
  18.     public void getUser() {  
  19.         User user = userService.getUser("zlex");  
  20.         if (logger.isDebugEnabled()) {  
  21.             logger.debug("user[" + user + "]");  
  22.         }  
  23.     }  
  24. }  

咱們作了什麼?Nothing!就跟調用通常Spring容器中的實現同樣! 
再看applicationContext.xml: 
Xml代碼  
  1. <bean  
  2.     id="userService"  
  3. class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">  
  4.     <property  
  5.         name="serviceUrl"  
  6.         value="http://localhost:8080/spring/service/userTest" />  
  7.     <property  
  8.         name="serviceInterface"  
  9.         value="org.zlex.spring.httpinvoke.service.UserService" />  
  10. </bean>  

這裏咱們能夠經過Spring容器調用userService,而實際上,他是一個HttpInvokerProxyFactoryBean,在這個配置裏,定義了訪問地址serviceUrl,和訪問接口serviceInterface。 
執行測試! 
 
若是咱們這樣寫,其實默認調用了SimpleHttpInvokerRequestExecutor作實現,這個實現恐怕只能做爲演示來用! 
這也是效率問題所在!!! 
爲提升效率,應該經過Commons-HttpClient! 
咱們須要作什麼?導入這個jar,改改xml就行! 
Xml代碼 
  1. <bean  
  2.     id="userService"  
  3.     class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">  
  4.     <property  
  5.         name="serviceUrl"  
  6.         value="http://localhost:8080/spring/service" />  
  7.     <property  
  8.         name="serviceInterface"  
  9.         value="org.zlex.spring.httpinvoke.service.UserService" />  
  10.     <property  
  11.         name="httpInvokerRequestExecutor">  
  12.         <ref  
  13.             bean="httpInvokerRequestExecutor" />  
  14.     </property>  
  15. </bean>  
  16. <bean  
  17.     id="httpInvokerRequestExecutor" class="org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor">  
  18.     <property  
  19.         name="httpClient">  
  20.         <bean  
  21.             class="org.apache.commons.httpclient.HttpClient">  
  22.             <property  
  23.                 name="connectionTimeout"  
  24.                 value="2000" />  
  25.             <property  
  26.                 name="timeout"  
  27.                 value="5000" />  
  28.         </bean>  
  29.     </property>  
  30. </bean>  

經過HttpClient,咱們能夠配置超時時間timeout和鏈接超時connectionTimeout兩個屬性,這樣,服務器執行操做時,若是超時就能夠強行釋放鏈接,這樣可憐的tomcat不會由於HttpInvoke鏈接不釋放而被累死! 
回頭看了一眼我N多年前的代碼,萬歲,我當時確實是這麼實現的!好在沒有犯低級錯誤!!! 
執行操做! 
 
這時,轉爲org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor實現了! 
不過同事認爲,這個效率仍是不夠高!!! 
再改,改什麼?仍是xml! 
Xml代碼  
  1. <bean  
  2.         id="httpInvokerRequestExecutor"  
  3.         class="org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor">  
  4.         <property  
  5.             name="httpClient">  
  6.             <bean  
  7.                 class="org.apache.commons.httpclient.HttpClient">  
  8.                 <property  
  9.                     name="connectionTimeout"  
  10.                     value="2000" />  
  11.                 <property  
  12.                     name="timeout"  
  13.                     value="5000" />  
  14.                 <property  
  15.                     name="httpConnectionManager">  
  16.                     <ref  
  17.                         bean="multiThreadedHttpConnectionManager" />  
  18.                 </property>  
  19.             </bean>  
  20.         </property>  
  21.     </bean>  
  22.     <bean  
  23.         id="multiThreadedHttpConnectionManager"  
  24.         class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager">  
  25.         <property  
  26.             name="params">  
  27.             <bean  
  28.                 class="org.apache.commons.httpclient.params.HttpConnectionManagerParams">  
  29.                 <property  
  30.                     name="maxTotalConnections"  
  31.                     value="600" />  
  32.                 <property  
  33.                     name="defaultMaxConnectionsPerHost"  
  34.                     value="512" />  
  35.             </bean>  
  36.         </property>  
  37.     </bean>  

改用MultiThreadedHttpConnectionManager,多線程!!! 
測試就不說了,實踐證實: 
默認實現,服務器平均10s左右才能響應一個請求。 
多線程實現,服務器平均20ms左右響應一個請求。 
這簡直不是一個數量級!!! 

注意:在HttpClient的3.1版本中,已不支持以下配置,相應的方法已經廢棄! 
Xml代碼  
  1. <property    
  2.     name="connectionTimeout"    
  3.     value="2000" />    
  4. <property    
  5.     name="timeout"    
  6.     value="5000" />   


若是仔細看看文檔, 
引用
HttpClient that uses a default MultiThreadedHttpConnectionManager.

commons 系列的實現怎麼會不考慮多線程呢?人家默認實現就是多線程的!同事多慮了! 
固然,同事還補充了一句,須要控制鏈接數! 
難怪,這裏要設置 
Xml代碼  
  1. <bean  
  2.     class="org.apache.commons.httpclient.params.HttpConnectionManagerParams">  
  3.     <property  
  4.         name="maxTotalConnections"  
  5.         value="600" />  
  6.     <property  
  7.         name="defaultMaxConnectionsPerHost"  
  8.         value="512" />  
  9. </bean>  


默認啥狀況?
引用
maxConnectionsPerHost 每一個主機的最大並行連接數,默認爲2 
public static final int DEFAULT_MAX_HOST_CONNECTIONS = 2; 
maxTotalConnections 客戶端總並行連接最大數,默認爲20  
public static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 20;

 

--如下是藝術家補充java

增長一個service-servlet.xm(對應urlMap)l,放在web-inf目錄下 web

web.xml中配置  spring

<servlet>
		<servlet-name>service</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>service</servlet-name>
		<url-pattern>/service/*</url-pattern>
	</servlet-mapping>
相關文章
相關標籤/搜索