公司不同pool之间提供service都是通过hessian来开放接口的,个人觉得hessian的使用非常简单。做个demo如下:
0.首先创建web工程,并加载hessian.jar。
1.创建service,即我们通过它来提供接口:
1 | public interface BasicService { |
3 | public void setServiceName(String serverName); |
5 | public String getServiceName(); |
7 | public User createUser(); |
2.创建service实现:
01 | public class BasicServiceImpl implements BasicService { |
03 | private String serviceName; |
06 | public void setServiceName(String serverName) { |
07 | this .serviceName = serverName; |
11 | public String getServiceName() { |
12 | return this .serviceName; |
16 | public User createUser() { |
17 | return new User( "zhangsan" , "123456" ); |
3.创建需要通过hessian传递的对象(必须序列化):
01 | public class User implements Serializable { |
03 | private static final long serialVersionUID = 5792818254468116836L; |
05 | private String username; |
07 | private String password; |
09 | public User(String username, String password) { |
10 | this .username = username; |
11 | this .password = password; |
14 | public String getUsername() { |
18 | public void setUsername(String username) { |
19 | this .username = username; |
22 | public String getPassword() { |
26 | public void setPassword(String password) { |
27 | this .password = password; |
4.配置web.xml:
01 | <? xml version = "1.0" encoding = "UTF-8" ?> |
02 | < web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0" > |
03 | < display-name >HessianServer</ display-name > |
06 | < servlet-name >basic</ servlet-name > |
07 | < servlet-class >com.caucho.hessian.server.HessianServlet</ servlet-class > |
09 | < param-name >service-class</ param-name > |
10 | < param-value >com.loujinhe.service.impl.BasicServiceImpl</ param-value > |
15 | < servlet-name >basic</ servlet-name > |
16 | < url-pattern >/basic</ url-pattern > |
5.创建测试用例:
01 | import java.net.MalformedURLException; |
03 | import org.junit.Before; |
04 | import org.junit.Test; |
06 | import com.caucho.hessian.client.HessianProxyFactory; |
07 | import com.loujinhe.service.BasicService; |
10 | public class BasicServiceTest { |
12 | private BasicService basicService; |
15 | public void init() throws MalformedURLException { |
16 | HessianProxyFactory factory = new HessianProxyFactory(); |
17 | String url = "http://localhost:8080/HessianServer/basic" ; |
18 | basicService = (BasicService)factory.create(BasicService. class , url); |
22 | public void testBasic() { |
23 | basicService.setServiceName( "BasicService" ); |
24 | System.out.println(basicService.getServiceName()); |
26 | System.out.println(basicService.createUser().getUsername()); |
27 | System.out.println(basicService.createUser().getPassword()); |
6.启动服务器,运行测试用例,会得到如下结果:
BasicService
zhangsan
123456
来自:http://blog.csdn.net/loujinhe/article/details/8479238