---
title: "Spring HttpInvoke远程调用服务"
author: "salouhim"
date: "2011-07-05T16:12:19Z"
tags: []
categories: ["企业架构"]
slug: "spring-httpinvoke"
draft: true
lastmod: "2011-07-05T16:12:19Z"
id: 1115048
url: "https://salouhim.iteye.com/blog/1115048"
---

# Spring HttpInvoke实现和效率提升

*2*人收藏此文章， [收藏此文章]() 发表于3个月前 , 已有**143**次阅读 共[**0**](http://salouhim.iteye.com/admin/blogs/#comments)个评论 **2**人收藏此文章

Spring HttpInvoke，一种较为常用的、基于Spring架构的服务器之间的远程调用实现，可以说是轻量级的RMI。   
最初，我们使用Spring HttpInvoke同步配置数据，刷新多个服务器上的缓存，当然如果用分布式缓存是不是更好![](http://snowolf.javaeye.com/images/smiles/icon_smile.gif) ！   
使用Spring HttpInvoke，你可以调用远程接口，进行数据交互、业务逻辑操作等等。   
废话不说了，上代码！   
用户操作接口： 

Java代码  

01. /\**
02. * @author &lt;a href="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
03. * @since 1.0
04. \*/
05. public interface UserService {
06. /\**
07. * 获得用户
08. \*
09. * @param username
10. *            用户名
11. * @return
12. \*/
13. User getUser(String username);
14. }

用户类，注意实现**Serializable**接口，这是执行远程调用传递数据对象的第一要求——数据对象必须实现**Serializable**接口，因为，要执行序列化/反序列化操作！ 

Java代码  

01. /\**
02. * @author &lt;a href="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
03. * @since 1.0
04. \*/
05. public class User implements Serializable {
06. private static final long serialVersionUID = 5590768569302443813L;
07. private String username;
08. private Date birthday;
09. /\**
10. * @param username
11. * @param birthday
12. \*/
13. public User(String username, Date birthday) {
14. this.username = username;
15. this.birthday = birthday;
16. }
17. // 省略
18. /*
19. * (non-Javadoc)
20. \*
21. * @see java.lang.Object#toString()
22. \*/
23. @Override
24. public String toString() {
25. return String.format("%s\\t%s\\t", username, birthday);
26. }
27. }

覆盖toString()方法，输出用户信息！   
再看UserServiceImpl实现： 

Java代码  

01. /\**
02. * @author &lt;a href="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
03. * @since 1.0
04. \*/
05. public class UserServiceImpl implements UserService {
06. private Logger logger = Logger.getLogger(UserServiceImpl.class);
07. /*
08. * (non-Javadoc)
09. \*
10. * @see
11. * org.zlex.spring.httpinvoke.service.UserService#getUser(java.lang.String)
12. \*/
13. @Override
14. public User getUser(String username) {
15. if (logger.isDebugEnabled()) {
16. logger.debug("username:\[" + username + "]");
17. }
18. User user = new User(username, new Date());
19. if (logger.isDebugEnabled()) {
20. logger.debug("user:\[" + user + "]");
21. }
22. return user;
23. }
24. }

只把用户信息打出来即可说明调用效果！   
看applicationContext.xml 

Xml代码  

01. &lt;bean
02. id="userService"
03. class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter"&gt;
04. &lt;property
05. name="service"&gt;
06. &lt;bean
07. class="org.zlex.spring.httpinvoke.service.impl.UserServiceImpl" /&gt;
08. &lt;/property&gt;
09. &lt;property
10. name="serviceInterface"
11. value="org.zlex.spring.httpinvoke.service.UserService" /&gt;
12. &lt;/bean&gt;

我们要把userService暴露出去，这样外部就可以通过http接口调用这个接口的实现了。   
说说HttpInvokerServiceExporter，这个类用来在服务器端包装需要暴露的接口。   
熟悉service，定义具体的实现类！ 

Xml代码  

1. &lt;property
2. name="service"&gt;
3. &lt;bean
4. lass="org.zlex.spring.httpinvoke.service.impl.UserServiceImpl" /&gt;
5. &lt;/property&gt;

熟悉serviceInterface指向需要暴露的接口，注意使用value标注接口名称！ 

Xml代码 

1. &lt;property
2. name="serviceInterface"
3. value="org.zlex.spring.httpinvoke.service.UserService" /&gt;

最后再看service-servlet.xml配置 

Xml代码  

01. &lt;bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt;
02. &lt;property
03. name="urlMap"&gt;
04. &lt;map&gt;
05. &lt;entry
06. key="userTest"
07. value-ref="userService" /&gt;
08. &lt;/map&gt;
09. &lt;/property&gt;
10. &lt;/bean&gt;

直接将请求指向刚才配置的userService   
现在我们之间访问一下http://localhost:8080/spring/service/   
![](http://dl.javaeye.com/upload/attachment/271536/41b95a4d-10e6-3d61-9e3f-413272bc1705.jpg "点击查看原始大小图片")   
这就说明，服务器端配置已经成功了！如果在日志中频繁得到这种异常，那很可能服务器被恶意访问了！   
再看客户端实现： 

Java代码  

01. /\**
02. * @author &lt;a href="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
03. * @since 1.0
04. \*/
05. public class UserServiceTest {
06. private Logger logger = Logger.getLogger(UserServiceTest.class);
07. private ApplicationContext context;
08. private UserService userService;
09. @Before
10. public void initialize() {
11. context = new ClassPathXmlApplicationContext("applicationContext.xml");
12. userService = (UserService) context.getBean("userService");
13. }
14. @Test
15. public void getUser() {
16. User user = userService.getUser("zlex");
17. if (logger.isDebugEnabled()) {
18. logger.debug("user\[" + user + "]");
19. }
20. }
21. }

我们做了什么？Nothing！就跟调用一般Spring容器中的实现一样！   
再看applicationContext.xml： 

Xml代码  

01. &lt;bean
02. id="userService"
03. class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"&gt;
04. &lt;property
05. name="serviceUrl"
06. value="http://localhost:8080/spring/service/userTest" /&gt;
07. &lt;property
08. name="serviceInterface"
09. value="org.zlex.spring.httpinvoke.service.UserService" /&gt;
10. &lt;/bean&gt;

这里我们可以通过Spring容器调用userService，而实际上，他是一个**HttpInvokerProxyFactoryBean**，在这个配置里，定义了访问地址serviceUrl，和访问接口serviceInterface。   
执行测试！   
![](http://dl.javaeye.com/upload/attachment/271538/22432c90-4045-3223-bd4b-10c6f55602f2.jpg "点击查看原始大小图片")   
如果我们这样写，其实默认调用了**SimpleHttpInvokerRequestExecutor**做实现，这个实现恐怕只能作为演示来用！   
这也是效率问题所在！！！   
为提高效率，应该通过Commons-HttpClient！   
我们需要做什么？导入这个jar，改改xml就行！ 

Xml代码 

01. &lt;bean
02. id="userService"
03. class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"&gt;
04. &lt;property
05. name="serviceUrl"
06. value="http://localhost:8080/spring/service" /&gt;
07. &lt;property
08. name="serviceInterface"
09. value="org.zlex.spring.httpinvoke.service.UserService" /&gt;
10. &lt;property
11. name="httpInvokerRequestExecutor"&gt;
12. &lt;ref
13. bean="httpInvokerRequestExecutor" /&gt;
14. &lt;/property&gt;
15. &lt;/bean&gt;
16. &lt;bean
17. id="httpInvokerRequestExecutor" class="org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor"&gt;
18. &lt;property
19. name="httpClient"&gt;
20. &lt;bean
21. class="org.apache.commons.httpclient.HttpClient"&gt;
22. &lt;property
23. name="connectionTimeout"
24. value="2000" /&gt;
25. &lt;property
26. name="timeout"
27. value="5000" /&gt;
28. &lt;/bean&gt;
29. &lt;/property&gt;
30. &lt;/bean&gt;

通过HttpClient，我们可以配置超时时间timeout和连接超时connectionTimeout两个属性，这样，服务器执行操作时，如果超时就可以强行释放连接，这样可怜的tomcat不会因为HttpInvoke连接不释放而被累死！![](http://snowolf.javaeye.com/images/smiles/icon_smile.gif)   
回头看了一眼我N多年前的代码，万岁，我当时确实是这么实现的！好在没有犯低级错误！！！   
执行操作！   
![](http://dl.javaeye.com/upload/attachment/271559/3c6456dc-b2f1-3dc2-882d-1261b3aa38df.jpg "点击查看原始大小图片")   
这时，转为org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor实现了！   
不过同事认为，这个效率还是不够高！！！   
再改，改什么？还是xml！ 

Xml代码  

01. &lt;bean
02. id="httpInvokerRequestExecutor"
03. class="org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor"&gt;
04. &lt;property
05. name="httpClient"&gt;
06. &lt;bean
07. class="org.apache.commons.httpclient.HttpClient"&gt;
08. &lt;property
09. name="connectionTimeout"
10. value="2000" /&gt;
11. &lt;property
12. name="timeout"
13. value="5000" /&gt;
14. &lt;property
15. name="httpConnectionManager"&gt;
16. &lt;ref
17. bean="multiThreadedHttpConnectionManager" /&gt;
18. &lt;/property&gt;
19. &lt;/bean&gt;
20. &lt;/property&gt;
21. &lt;/bean&gt;
22. &lt;bean
23. id="multiThreadedHttpConnectionManager"
24. class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"&gt;
25. &lt;property
26. name="params"&gt;
27. &lt;bean
28. class="org.apache.commons.httpclient.params.HttpConnectionManagerParams"&gt;
29. &lt;property
30. name="maxTotalConnections"
31. value="600" /&gt;
32. &lt;property
33. name="defaultMaxConnectionsPerHost"
34. value="512" /&gt;
35. &lt;/bean&gt;
36. &lt;/property&gt;
37. &lt;/bean&gt;

改用**MultiThreadedHttpConnectionManager**，多线程！！！   
测试就不说了，实践证明：   
默认实现，服务器平均10s左右才能响应一个请求。   
多线程实现，服务器平均20ms左右响应一个请求。   
这简直不是一个数量级！！！ 

**注意：在HttpClient的3.1版本中，已不支持如下配置，相应的方法已经废弃！** 

Xml代码  

1. &lt;property
2. name="connectionTimeout"
3. value="2000" /&gt;
4. &lt;property
5. name="timeout"
6. value="5000" /&gt;

如果仔细看看文档， 

引用

HttpClient that uses a default MultiThreadedHttpConnectionManager.

commons 系列的实现怎么会不考虑多线程呢？人家默认实现就是多线程的！同事多虑了！   
当然，同事还补充了一句，需要控制连接数！   
难怪，这里要设置 

Xml代码  

1. &lt;bean
2. class="org.apache.commons.httpclient.params.HttpConnectionManagerParams"&gt;
3. &lt;property
4. name="maxTotalConnections"
5. value="600" /&gt;
6. &lt;property
7. name="defaultMaxConnectionsPerHost"
8. value="512" /&gt;
9. &lt;/bean&gt;

默认啥情况？

引用

maxConnectionsPerHost 每个主机的最大并行链接数，默认为2   
public static final int DEFAULT\_MAX\_HOST\_CONNECTIONS = 2;   
maxTotalConnections 客户端总并行链接最大数，默认为20    
public static final int DEFAULT\_MAX\_TOTAL\_CONNECTIONS = 20;

 

--以下是艺术家补充

增加一个service-servlet.xm(对应urlMap)l,放在web-inf目录下 

web.xml中配置  

`1` `<servlet>`

`2` `<servlet-name>service</servlet-name>`

`3` `<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>`

`4` `<load-on-startup>1</load-on-startup>`

`5` `</servlet>`

`6` `<servlet-mapping>`

`7` `<servlet-name>service</servlet-name>`

`8` `<url-pattern>/service/*</url-pattern>`

`9` `</servlet-mapping>`