Hessian官网:http://hessian.caucho.com/ java
hessian是二进制web service协议。web
建立Hessian服务包括四个步骤:api
<!--more-->数组
public interface BasicAPI { public String hello(); }
public class BasicService extends HessianServlet implements BasicAPI { private String _greeting = "Hello, world"; public void setGreeting(String greeting) { _greeting = greeting; } public String hello() { return _greeting; } }
String url = "http://hessian.caucho.com/test/test"; HessianProxyFactory factory = new HessianProxyFactory(); BasicAPI basic = (BasicAPI) factory.create(BasicAPI.class, url); System.out.println("hello(): " + basic.hello());
<web-app> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class> <init-param> <param-name>home-class</param-name> <param-value>example.BasicService</param-value> </init-param> <init-param> <param-name>home-api</param-name> <param-value>example.Basic</param-value> </init-param> </servlet> <servlet-mapping> <url-pattern>/hello</url-pattern> <servlet-name>hello</servlet-name> </servlet-mapping> </web-app>
Hessian类能够用来作序列化与反序列化app
Object obj = ...; OutputStream os = new FileOutputStream("test.xml"); Hessian2Output out = new Hessian2Output(os); out.writeObject(obj); os.close();
InputStream is = new FileInputStream("test.xml"); Hessian2Input in = new Hessian2Input(is); Object obj = in.readObject(null); is.close();
若是要序列化比基础类型或String类型更加复杂的java对象,务必确保对象实现了java.io.Serializable接口。分布式
分布式应用须要发送大量二进制数据时,使用InputStream会更加有效率,由于它避免了分配大量byte数组。方法
参数中只有最后一个参数多是InputStream,由于数据是在调用过程当中读的。url
下面是一个上传文件的API的例子spa
package example; public interface Upload { public void upload(String filename, InputStream data); }
若是返回结果是InputStream,客户端必须在finally块中调用InputStream.close()方法,由于Hessian不会关闭
底层HTTP流,直到全部数据被读取而且input stream被关闭。.net
文件下载API: package example; public interface Download { public InputStream download(String filename, InputStream data); } 文件下载实现: InputStream is = fileProxy.download("test.xml"); try { ... // read data here } finally { is.close(); }