Hessian学习

Hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能. 相比WebService,Hessian更简单、快捷。

采用的是二进制RPC协议,因为采用的是二进制协议,所以它很适合于发送二进制数据。项目中实际使用直接传输Map<String,String>很方便。

手机端调用也很方便。

hession的包下载地址:http://hessian.caucho.com/#Java

我下载的hessian-3.1.6.jar

在spring中使用。以下的代码内容参照这个官网http://hessian.caucho.com的实验。我用的是spring mvc框架测试的spring2.5

下的4版本的hession版本好像有冲突就用3.1的了。

1.创建接口AppHessianService.java

/**
 * 
 * @ClassName  AppHessianService
 * @package com.open.service.hessian
 * @description
 * @author  fairyhawk
 * @Create Date: 2012-10-23 下午03:40:16
 *
 */
public interface AppHessianService {
    public Map<String, String> getUserInfo(Map<String, String> map);
}

2.实现类AppHessianServiceImpl.java

/**
 * ClassName  AppHessianServiceImpl
 *
 * History
 * Create User: liuqg
 * Create Date: 2012-10-23
 * Update User:
 * Update Date:
 */
package com.open.service.hessian;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.caucho.hessian.server.HessianServlet;

/**
 * 
 * @ClassName AppHessianServiceImpl
 * @package com.open.service.hessian
 * @description
 * @author fairyhawk 
 * @Create Date: 2012-10-23 下午03:40:31
 * 
 */
@Service("appHessianService")
public class AppHessianServiceImpl extends HessianServlet implements AppHessianService {
    private static final long serialVersionUID = 6307609125433956670L;

    @Override
    public Map<String, String> getUserInfo(Map<String, String> map) {
        String userId = map.get("userId");
        // 根据userId进行业务处理。查询数据库等
        Map<String, String> result = new HashMap<String, String>();
        result.put("name", userId + "-" + "theName");
        result.put("date", new Date().toString());
        return result;
    }

}


3.web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<!-- 配置文件加载 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath*:applicationContext_web.xml<!-- 前台项目db配置 -->
			<!-- classpath*:applicationContext_admin.xml 后台项目db配置 -->
		</param-value>
	</context-param>
	<!--spring监听 -->
	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	
	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>
			org.springframework.web.filter.CharacterEncodingFilter
		</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>false</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>*.do</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>
	
	 <!-- Spring MVC, start with DispatcherServlet 
	 the default context location : /WEB-INF/{servlet-name}-servlet.xml -->
	
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		 <!--<init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath*:springmvc-config.xml
            </param-value>
        </init-param>
        
		--><load-on-startup>2</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<!-- hessian 配置  默认会加载hessian-servlet.xml-->
	<servlet>
	<servlet-name>hessian</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	<servlet-name>hessian</servlet-name>
	<url-pattern>/hessian/*</url-pattern>
	</servlet-mapping>
	<!-- hessian 配置 -->
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <error-page>
		<error-code>404</error-code>
		<location>/404.html</location>
	</error-page>
	
	<error-page>
		<error-code>500</error-code>
		<location>/500.html</location>
	</error-page>
	
</web-app>

4.hessian-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<!-- ①:对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
	<context:component-scan base-package="com.open">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Service" />
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Repository" />
	</context:component-scan>

 <bean id="appHessianService" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target">
            <bean class="com.open.service.hessian.AppHessianServiceImpl">
            </bean>
        </property>
        <property name="proxyInterfaces">
            <value>
                com.open.service.hessian.AppHessianService
            </value>
        </property>
    
    </bean>
	<!-- ② Hessian接口网关 -->
	<bean name="/hessianService" class="com.open.service.hessian.OpenHessianExporter">
		<property name="service" ref="appHessianService" />
		<property name="serviceInterface">
			<value>com.open.service.hessian.AppHessianService</value>
		</property>
	</bean>
	
</beans>

5.HessianServiceExporter.java

package com.open.service.hessian;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.remoting.caucho.HessianServiceExporter;

/**
 * 
 * @ClassName OpenHessianExporter
 * @package com.open.service.hessian
 * @description
 * @author fairyhawk
 * @Create Date: 2012-10-23 下午06:25:17
 * 
 */

public class OpenHessianExporter extends HessianServiceExporter {

    public static final Log logger = LogFactory.getLog(OpenHessianExporter.class);

    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 此处可以根据自己的业务来做验证路径密钥等
String auth = request.getHeader("hessianAuth");//比较auth是否符合条件。否则是非法的请求 
 logger.info("++++++++ OpenHessianExporter invocate");
        super.handleRequest(request, response);
    }
}

6.测试类TestHessian.java
package com.test;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import com.caucho.hessian.client.HessianProxyFactory;
import com.open.service.hessian.AppHessianService;

public class TestHessian {
    public static void main(String[] args) {

        HessianProxyFactory factory = new HessianProxyFactory();
        try {
            AppHessianService appHessianService = (AppHessianService) factory.create(
                    AppHessianService.class,
                    "http://127.0.0.1/smvc/hessian/hessianService");
            Map<String, String> args1 = new HashMap<String, String>(1);
            args1.put("userId", "1234");
            Map<String, String> map = appHessianService.getUserInfo(args1);
            System.out.println(map.get("name"));
            System.out.println(map.get("date"));

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

7.在项目B中实际使用的时候,将A项目的接口类AppHessianService.java复制到B中。

 7.1添加配置文件

<!-- 客户端配置  Hessian接口 -->
	<bean id="client.hessianService"
		class="org.springframework.remoting.caucho.HessianProxyFactoryBean">
		<property name="serviceInterface"
			value="com.client.AppHessianService"></property>
		<property name="serviceUrl">
			<value>http://127.0.0.1/smvc/hessian/hessianService</value>
		</property>
		<property name="readTimeout">
			<value>100000</value>
		</property>
		<!-- Hessian 权限认证 -->
		<property name="proxyFactory">
			<bean class="com.client.ClientHessianProxyFactory" />
		</property>
	</bean>

7.2.ClientHessianProxyFactory.java

package com.client.hessian;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import com.caucho.hessian.client.HessianProxyFactory;

/**
 * 
 * @ClassName  CilentHessianProxyFactory
 * @package com.client.hessian
 * @description
 * @author  fairyhawk
 * @Create Date: 2012-10-23 下午07:09:42
 *
 */
public class ClientHessianProxyFactory extends HessianProxyFactory {


    @Override
    protected URLConnection openConnection(URL url) throws IOException {
        URLConnection conn = super.openConnection(url);
        //此处可根据需要设置密钥等=
        conn.setRequestProperty("hessianAuth", "aaaaaaa");
        return conn;
    }

}

7.3测试action

package com.open.action.user;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.open.service.hessian.AppHessianService;

@Controller
public class TestHessianAction {
    @Resource(name="client.hessianService")
    private AppHessianService appHessianService;
    
    @RequestMapping(value="/testHession.do")
    public String testHessianClient() {
        System.out.println("++++++ hello ++++++");
        Map<String, String> args1 = new HashMap<String, String>(1);
        args1.put("userId", "1234");
        Map<String, String> map = appHessianService.getUserInfo(args1);
        System.out.println(map.get("name"));
        return "/";
    }

}


综上服务端项目A需要配置1-6步骤。

客户端B调用的需要配置7.1-7.3 三个步骤(AppHessianService.java要从A复制到B中,路径随便我是放到com.client中了)




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值