Hessian使用C/S方式,基于HTTP协议传输,使用Hessian二进制序列化。
添加依赖:
<dependency><groupId>com.caucho</groupId><artifactId>hessian</artifactId><version>4.0.7</version>
</dependency>
服务端使用Web服务tomcat:
<web-app><servlet><servlet-name>HessianServlet</servlet-name><servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class><init-param><param-name>service-class</param-name><param-value>com.itheima.service.impl.UserServiceImpl</param-value></init-param></servlet><servlet-mapping><servlet-name>HessianServlet</servlet-name><url-pattern>/hessianServlet</url-pattern></servlet-mapping></web-app>
注意web-app中的servlet写法
package com.itheima.service;public interface UserService {String sayHello(String name);
}
package com.itheima.service.impl;import com.itheima.service.UserService;public class UserServiceImpl implements UserService {@Overridepublic String sayHello(String name) {return name + "调用了服务端sayHello方法";}
}
Hessian_client
package com.itheima;import com.caucho.hessian.client.HessianProxyFactory;
import com.itheima.service.UserService;import java.net.MalformedURLException;public class HessianMain {public static void main(String[] args) throws MalformedURLException {String url = "http://localhost:8080/hessianServlet";HessianProxyFactory factory = new HessianProxyFactory();UserService service = (UserService) factory.create(UserService.class, url);String hello = service.sayHello("客户端");System.out.println(hello);}
}
注意和RMI一样,都需要将服务端的UserService接口复制到客户端,路径包名要一直,否则报错:
启动Server:
执行客户端main方法
执行结果::
客户端调用了服务端sayHello方法