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(); }