使用Hessian来进行远程调用

Hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能. Spring也对Hessian进行了支持,以下就用一个简单的例子来说明下如何在Spring中使用Hessian吧。

Hessian的服务端配置:

在服务端的某个applicationContext-*.xml(命名不限)创建HessianServiceExporter来暴露你的服务接口(接口以及接口实现类略):

<!-- RemoteService的Hessian Exporter -->
	<bean name="remoteServiceExporter" class="org.springframework.remoting.caucho.HessianServiceExporter">
		<property name="service" ref="xxxRemoteService" />
		<property name="serviceInterface" value="com.nineclient.talk.service.xxxRemoteService" />

	</bean>

	<!-- 服务接口的实现Bean定义 -->
	<bean id="xxxRemoteService" class="com.nineclient.talk.service.impl.JtalkRemoteServiceImpl" />

 在web.xml中为Exporter定义一个相应的Servlet,目的是为了将这个Exporter映射到一个url地址中,但这个Servlet的名称需和这个Exporter bean的name一样!

<servlet>
    <servlet-name>remoteServiceExporter</servlet-name>
    <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>remoteServiceExporter</servlet-name>
    <url-pattern>/remoting/xxxRemoteservice</url-pattern>
  </servlet-mapping>
   <servlet>

Hessian客户端的配置:

1)把服务端的接口(实现类不需要)打包成jar给客户端

2)在一个配置文件如config.properties中,配置远程服务的地址,如:

HESSIAN_REMOTESERVICE_URL=http://ip:port/serverName/remoting/xxxRemoteservice

2)不妨写一个工具类来获得远程服务的调用地址

public class RemoteHessianUtil {
	public static HessianProxyFactory factory;
	public static String url;
	static {
		factory = new HessianProxyFactory();
		factory.setOverloadEnabled(true);
		url = PropertyReader.getProperty("HESSIAN_REMOTESERVICE_URL");//读取配置文件属性并把这些属性放入map中过程略。。
	}
	
	public static Object create(Class<?> api, String urlName) {
		try {
			return factory.create(api, urlName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//获取远程调用服务的方法
	public static xxxRemoteService getRemoteService() {
		return (xxxRemoteService) RemoteHessianUtil.create(xxxRemoteService.class, url);
	}
	
}

 做完这些,依次启动服务端和客户端,就可以做简单的远程调用了。当服务端接口更新,需要重新打包给客户端。

 

猜你喜欢

转载自raising.iteye.com/blog/2335017
今日推荐