Hessian可以单独使用,不依赖于spring,由于工作中所使用服务提供方和服务调用方都是用spring作为容器的,所以本文先介绍一下hessian整合Spring的用法
一:服务提供端
1、jar包依赖 pom.xml (与spring整合需要spring-webmvc包依赖)
<dependency> <groupId>com.caucho</groupId> <artifactId>hessian</artifactId> <version>4.0.33</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.5.RELEASE</version> </dependency>
2、Web.xml的配置(配置请求的拦截,与配置文件的位置)
<servlet> <servlet-name>remote</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/remote-ref.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>remote</servlet-name> <url-pattern>/remote/*</url-pattern> </servlet-mapping>
3、写服务接口及实现类(实现类示例如下)
@Service("testService") public class TestServiceImpl implements TestService { @Resource private MenuQueryManager menuQueryManager; @Override public String getValue() { return "hello world"; } @Override public Timestamp getCurrentDate() { return DateUtil.getCurrentTimestamp(); } }
4、对外提供服务的配置文件remote-ref.xml(文件名来源是web.xml中配置的文件名)
<?xml version="1.0" encoding="UTF-8"?> <beans …> <!-- 对外提供的接口,name为请求路径,class固定不变 --> <bean name="/testService" class="org.springframework.remoting.caucho.HessianServiceExporter"> <!—service配置服务类,即服务实现类注解所标示的名称,serviceInterface为服务类的接口 --> <property name="service" ref="testService"/> <property name="serviceInterface" value="com.xxx.xxx.remote.TestService"/> </bean> </beans>
二:服务使用方
1、jar包依赖 pom.xml
<dependency> <groupId>com.caucho</groupId> <artifactId>hessian</artifactId> <version>4.0.33</version> </dependency>
2、接口依赖包(从服务端抽取接口jar包),然后加入classpath中
3、配置加载web.xml(名称随便,spring能加载该配置文件即可
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml,classpath:remote-service.xml</param-value> </context-param>
4、远程服务配置remote-service.xml
<!-- id为远程服务的名称,class固定 --> <bean id="testService" class="org.springframework.remoting.caucho.HessianProxyFactoryBean"> <!-- 接口的远程地址 --> <property name="serviceUrl" value="http://127.0.0.1:8080/test/remote/testService"/> <!-- 接口名称 --> <property name="serviceInterface" value="com.xxx.xxx.remote.TestService"/> </bean>
http://127.0.0.1:8080/test/remote/testService标红的这部分为服务端配置服务的bean的name
5、客户端调用
@Controller("testAction") @Scope("prototype") public class TestAction extends ActionSupport { @Resource private com.xxx.xxx.remote.TestService testService; @Override public String execute() throws Exception { System.out.println(testService.getValue()); System.out.println(testService.getCurrentDate()); return null; } }