Hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能。 相比WebService,Hessian更简单、快捷。采用的是二进制RPC协议,因为采用的是二进制协议,所以它很适合于发送二进制数据。
HessianServer的实现:
传输的实体需要实现Serializable接口.
package yzr.Entity;
import java.io.Serializable;
public class UserEntity implements IEntity,Serializable {
public UserEntity(){}
private String name;
private String eMail;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public String sayHello(){
return "Hello World,I'm "+this.name;
};
}
ServiceAPI:
package yzr.ServiceAPI;
import yzr.Entity.IEntity;
public interface IService {
IEntity GetData();
}
ServiceImpl:
package yzr.ServiceImpl;
import yzr.Entity.IEntity;
import yzr.Entity.UserEntity;
import yzr.ServiceAPI.IService;
public class MyService implements IService {
@Override
public IEntity GetData() {
UserEntity userEntity=new UserEntity();
userEntity.setName("YZR");
userEntity.seteMail("2437676796@qq.com");
return userEntity;
}
}
将服务通过HessianServlet发布出去:
<servlet>
<servlet-name>myService</servlet-name>
<servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>
<init-param>
<param-name>service-class</param-name>
<param-value>yzr.ServiceImpl.MyService</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>
myService
</servlet-name>
<url-pattern>
/myService
</url-pattern>
</servlet-mapping>
HessianClient的实现:
传输的实体和ServiceAPI必须要和服务端保持一致:
调用服务端的服务:
package yzr.Test;
import java.net.MalformedURLException;
import org.junit.Test;
import yzr.Entity.IEntity;
import yzr.Entity.UserEntity;
import yzr.ServiceAPI.IService;
import com.caucho.hessian.client.HessianProxyFactory;
public class App {
@Test
public void test(){
String url ="http://127.0.0.1:8080/HessianServer/myService";
HessianProxyFactory factory = new HessianProxyFactory();
try {
IService service = (IService) factory.create(IService.class, url);
IEntity entity=service.GetData();
if(entity!=null){
System.out.println(entity.sayHello());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
项目结构:
测试:
首先将Hessian服务端发布到Tomcat服务器中运行起来,然后执行HessianClient客户端Test方法.
代码下载: