Hessian RPC Sample and Hessian serialized object transfer based on HTTP request

Source: Internet
Author: User
Tags http post

This article mainly introduces two cases, the first is to use Hessian to implement the remote procedure call, the second is the binary RPC protocol provided by Hessian and the servlet for data interaction, Hessian itself is an HTTP-based RPC implementation.


Case one:

1. Preparatory work

Here you build a MAVEN project that contains four modules, the parent module (only used to aggregate other modules, not actually used), server-side modules, client modules, API modules (remote process interfaces for server and client use). Directory structure See:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/58/73/wKiom1SwmzSRUDR1AAHOPhvwsXI742.jpg "title=" Rpc.png "alt=" Wkiom1swmzsrudr1aahophvwsxi742.jpg "/>

2. Adding Hessian dependencies

Since both the client and the server depend on the Hessian package, this can be added to the pom.xml of the parent module.

<dependency><groupId>com.caucho</groupId><artifactId>hessian</artifactId>< Version>4.0.38</version></dependency>


For other specific dependency configurations, there is no superfluous display here, complete at the end of this article.


3. Define the process interface in the HESSIAN-API module

Package Secondriver.hessian.api;import Java.io.inputstream;import Java.util.list;import Secondriver.hessian.api.bean.person;public interface Hellohessian {public String SayHello ();p ublic string SayHello ( String name);p ublic list<person> getpersons ();p ublic person Getpersonbyid (int id);p ublic boolean uploadfile ( string filename, inputstream data);p ublic byte[] DownloadFile (string filename);

The above interface defines six methods, there are overloaded methods, have get collection, have get object, have upload file, download file and so on. It is important to note that the input output stream object parameter should be placed in the last parameter of the method when defining the method of the procedure interface in Hessian. In addition, in the actual operation found that the processing of the stream through the remote call or there will be a puzzling problem, plus hessian lack of complete documentation (in addition to the Hessian serial number protocol).


The definition of this method of downloading a file uses a return byte array, which will be limited to the memory of the virtual machine or other factors. Online has said about file download Hessian not supported (failed to confirm. Extension case two of the way, the transmission of binary can be implemented to download, but this will be unrelated to Hessian RPC implementation, but applied to the Hessian serial number protocol, this can be considered a strategy, so, about remote file download, who will use such a way?!!


4. Server-side implementation of specific functions


Server-Side Implementation interface

Package secondriver.hessian.server.bo;import java.io.file;import java.io.fileinputstream;import  java.io.filenotfoundexception;import java.io.ioexception;import java.io.inputstream;import  java.util.Arrays;import java.util.Calendar;import java.util.Date;import java.util.List; import java.util.random;import org.apache.commons.io.fileutils;import  org.apache.commons.io.ioutils;import secondriver.hessian.api.hellohessian;import  Secondriver.hessian.api.bean.person;public class hellohessianimpl implements hellohessian  {private static Person[] persons = new Person[5];static {Random  Random = new random ();for  (int i = 0, l = persons.length;  i < l; i++)  {persons[i] = new person ();p Ersons[i].setid (i);p ersons [I].setgender (Random.nextboolean ());p ersons[i].setname ("name-" &NBsp;+ i);p Ersons[i].setphone (Random.nextlong ());p Ersons[i].setheight (random.nextdouble ());p Ersons[i]. Setweight (Random.nextfloat ());p ersons[i].setaddress (new string[] {  "Address"  +  Random.nextint (), "Address"  + random.nextint ()  }); Calendar c = calendar.getinstance (); C.set (calendar.date, i + 1);p ersons[i]. Setbrithday (C.gettime ());}} @Overridepublic  string sayhello ()  {return  "hello hession "  + new  Date (). toString ();} @Overridepublic  string sayhello (string name)  {return  "welcome "  + name ;} @Overridepublic  list<person> getpersons ()  {return arrays.aslist (persons);} @Overridepublic  person getpersonbyid (int id)  {for  (person p : persons)  {if  (P.getid ()  == id)  {return p;} Return null;} @Overridepublic  boolean uploadfile (String filEname, inputstream data)  {List<String> temp;try {temp =  Ioutils.readlines (data); String filepath = system.getproperty ("User.dir")  +  "/temp/" + filename; Fileutils.writelines (New file (FilePath),  temp); System.out.println ("upload file to "  + filepath); return true;}  catch  (ioexception e)  {e.printstacktrace (); return false;}} @Overridepublic  byte[] downloadfile (string filename)  {String filePath =  System.getproperty ("User.dir")  +  "/temp/"  + fileName;InputStream data =  Null;try {data = new fileinputstream (FilePath); int size = data.available (); Byte[] buffer = new byte[size];ioutils.read (data, buffer); return buffer;}  catch  (filenotfoundexception e)  {e.printstacktrace (); return null;}  catch  (Ioexception e)  {e.printstacktrace (); return null;}  finally {ioutils.closequietly (data);}}}


5. Server-side configuration remote service address


Hessian is a remote on HTTP tool, the server is a typical Java Web application, we need to configure the service's request address in Web. Xml.

<servlet><servlet-name>HelloHessian</servlet-name><servlet-class> com.caucho.hessian.server.hessianservlet</servlet-class><!--RPC Hessianservlet processing class--><init-param ><param-name>home-class</param-name><!--Remote Service implementation class--><param-value> secondriver.hessian.server.bo.hellohessianimpl</param-value></init-param><init-param>< param-name>home-api</param-name><!--Remote Service Interface--><param-value> Secondriver.hessian.api.hellohessian</param-value></init-param></servlet>


6. Client invoke remote object method

package secondriver.hessian.client;import java.io.bufferedinputstream;import  java.io.fileinputstream;import java.io.filenotfoundexception;import java.io.filewriter;import  java.io.ioexception;import java.io.inputstream;import java.net.malformedurlexception;import  java.util.list;import org.apache.commons.io.ioutils;import secondriver.hessian.api.hellohessian; import secondriver.hessian.api.bean.person;import com.caucho.hessian.client.hessianproxyfactory;/**  * Hessian RPC */public class HelloHessianClient {public static  string urlname =  "Http://localhost:8080/hessian-server/HelloHessian";p ublic static  Void main (String[] args)  throws MalformedURLException {HessianProxyFactory  Factory = new hessianproxyfactory ();//  Open method overload factory.setoverloadenabled (TRUE); hellohessian hellohession =  (Hellohessian) factory.create (Hellohessian.class, urlname);//  call method System.out.println ("Call sayhello ():"  + hellohession.sayhello ()); System.out.println ("Call sayhello (\" tom\ "):" + hellohession.sayhello ("Tom")); System.out.println ("Call getpersons ():");//  call method to get collection object list<person> persons =  Hellohession.getpersons ();if  (Null != persons && persons.size ()  >  0)  {for  (person p : persons)  {system.out.println (p.tostring ());}}  else {system.out.println ("No person.");   Get object int id = 2; by parameter call method System.out.println (String.Format ("Call getpersonbyid (%d)",  id)); Person person = hellohession.getpersonbyid (ID);if  (null != person)  { System.out.println (Person.tostring ());}  else {system.out.println ("id is "  + id +  " person not  exist. ");   Upload File String filename =  "Upload.txt"; String filepath = system.getproperty ("User.dir")  +  "/temp/"  + filename;i Nputstream data = null;try {data = new bufferedinputstream (new  FileInputStream (FilePath));if  (Hellohession.uploadfile (Filename, data))  {system.out.println (" upload file  " + filePath + "  succeed ");}  else {system.out.println ("upload file "  + filePath +  " failed.");}  catch  (filenotfoundexception e)  {e.printstacktrace ();}  finally {ioutils.closequietly (data);}   Download file filename =  "Download.txt"; Filepath = system.getproperty ("User.dir")  +   "/temp/"  + filename;try {byte[] temp = hellohession.downloadfile (fileName) ;if  (null != temp)  {filewriter output = new filewriter (FilePath); IOUtiLs.write (temp, output,  "UTF-8"); System.out.println ("download file "  + filePath +  " succeed."); O Utput.close ();}  else {system.out.println ("download file "  + filePath +  " failed.");}  catch  (ioexception e)  {e.printstacktrace ();}}


The client-side invocation shows that the specific implementation of the remote method is transparent to the client.


7. Running the program

7.1 Starting the server

7.2 Running the client program

The client requests the result of the remote service object method call:

Call SayHello (): Hello hession Sat Jan 12:31:21 CST 2015call sayHello ("Tom"): Welcome tomcall getpersons ():P Erson [Id=0, Gender=true, name=name-0, Brithday=thu Jan 12:31:21 CST, height=0.04756537639163749, weight=0.24559122, phone= 1359341198036930408, address=[address2145973789, Address486043733] .... Omit Call Getpersonbyid (2) person [id=2, Gender=false, name=name-2, Brithday=sat Jan 12:31:21 CST, height=0.071694514 40704722, weight=0.8515671, phone=2732762596557481818, address=[address8744397, address-1690316438]]upload file F:\_ _eclipse\tomsworkspace\hessian-l-parent\hessian-client/temp/upload.txt succeed. Download file F:\__eclipse\tomsworkspace\hessian-l-parent\hessian-client/temp/download.txt succeed.



Case TWO:


1. The client serializes the object through the Hessian serial number protocol, submits it to the server side via an HTTP post, and then deserializes the server-side response data.

package secondriver.hessian.data;import java.io.bytearrayoutputstream;import  java.io.inputstream;import java.util.date;import org.apache.http.httpentity;import  org.apache.http.client.methods.closeablehttpresponse;import org.apache.http.client.methods.httppost; import org.apache.http.entity.bytearrayentity;import org.apache.http.entity.contenttype;import  Org.apache.http.impl.client.closeablehttpclient;import org.apache.http.impl.client.httpclients;import  secondriver.hessian.api.bean.Person;import com.caucho.hessian.io.Hessian2Input;import  com.caucho.hessian.io.hessian2output;public class test3 {public static string  urlname =  "Http://localhost:8080/hessian-server/PostDataServlet";p ublic static void  Main (String[] args)  throws Throwable {//  serialization bytearrayoutputstream os =  new bytearrayoutputstream (); Hessian2output h2o&nbSp;= new hessian2output (OS); H2o.startmessage (); H2o.writeobject (Getperson ()); H2o.writestring ("I  Am client. "); H2o.completemessage (); H2o.close (); Byte[] buffer = os.tobytearray (); Os.close (); Bytearrayentity bytearrayentity = new bytearrayentity (Buffer,contenttype.create (" X-application/hessian ", " UTF-8 ")); Closeablehttpclient client = httpclients.createdefault (); Httppost post = new httppost (urlname);p ost.setentity (bytearrayentity); Closeablehttpresponse response = client.execute (POST); System.out.println ("response status:\n" + response.getstatusline (). Getstatuscode ()); Httpentity body = response.getentity (); Inputstream is = body.getcontent (); Hessian2input h2i = new hessian2input (IS); H2i.startmessage (); person person =  (person)  h2i.readobject (); System.out.println ("response:\n"  + person.tostring ()); SystEm.out.println (H2i.readstring ()); H2i.completemessage (); H2i.close (); Is.close ();} Public static person getperson ()  {person person = new person (); Person.setaddress (new string[] {  "Beijing",  "TaiWan",  "GuangZhou" &NBSP;}); Person.setbrithday (New date ());p Erson.setgender (False);p Erson.setheight (168.5D);p Erson.setid (300); Person.setname ("Jack");p Erson.setphone (188888888);p erson.setweight (55.2F); Return person;}}


2. The server side deserializes the object through the Hessian serialization protocol, responds to the request by HttpServletResponse, and the response data is a binary result of Hessian serialization.

package secondriver.hessian.server.servlet;import java.io.bytearrayoutputstream;import  java.io.ioexception;import java.util.date;import javax.servlet.servletexception;import  javax.servlet.servletinputstream;import javax.servlet.servletoutputstream;import  javax.servlet.http.httpservlet;import javax.servlet.http.httpservletrequest;import  javax.servlet.http.httpservletresponse;import secondriver.hessian.api.bean.person;import  com.caucho.hessian.io.hessian2input;import com.caucho.hessian.io.hessian2output;public class  postdataservlet extends httpservlet {private static final long  serialversionuid = -4461061053732328507l; @Overrideprotected  void dopost (httpservletrequest &NBSP;REQ,&NBSP;HTTPSERVLETRESPONSE&NBSP;RESP) throws servletexception, ioexception {//  Processing request Servletinputstream sis = req.getinputstream (); Hessian2input h2i&nbSp;= new hessian2input (SIS); H2i.startmessage (); person person =  (person)  h2i.readobject (); System.out.println ("receive:\n"  + person.tostring ()); System.out.println (H2i.readstring ()); H2i.completemessage (); H2i.close (); Sis.close ();//  Send Response resp.setcharacterencoding ("UTF-8"); Resp.setcontenttype ("X-application/hessian"); Bytearrayoutputstream bos = new bytearrayoutputstream (); Hessian2output h2o = new hessian2output (BOS); H2o.startmessage (); H2o.writeObject (GetPerson ( )); H2o.writestring ("I am server."); H2o.completemessage (); H2o.close (); Servletoutputstream sos = resp.getoutputstream (); Sos.write (Bos.tobytearray ()); Sos.flush (); Bos.close (); Sos.close ();} Public static person getperson ()  {person person = new person (); Person.setaddress (new string[] {  "Shanghai",  "ShenZhen",  "Chengdu" &NBSP;}); Person.setbrithday (New date ());p erson.seTgender (True);p erson.setheight (178.5D);p Erson.setid (301);p Erson.setname ("Tom");p Erson.setphone (188218888); Person.setweight (55.2F); Return person;}}

3. Configure Postdataservlet in Web. XML, omitting specific configuration information here, and refer to the Hellohessian servlet configuration above.

4. Running the program

4.1 Starting the server

4.2 Run the client program TEST3.

Operation Result:

Server-Side output:

[INFO] Restart completed at Sat Jan 12:34:51 CST 2015receive:person [id=300, Gender=false, Name=jack, Brithday=sat Jan 10 12:3 5:03 CST, height=168.5, weight=55.2, phone=188888888, address=[beijing, TaiWan, guangzhou]]i am client.

Client output:

Response Status:200response:person [id=301, Gender=true, Name=tom, Brithday=sat Jan 12:35:03 CST, height=178.5, we ight=55.2, phone=188218888, Address=[shanghai, ShenZhen, chengdu]]i am server.


The analysis output shows that the Hessian serialized object is transmitted over HTTP and successfully deserialized.

For Hessian serial number Protocol See also: http://hessian.caucho.com/doc/hessian-serialization.html


Written in the end: Hessian the relevant information on the Internet is still relatively small, and the examples are not the same, and the official document error is clearly visible (carefully read to a glance), this article from the Hessian RPC use and Hessian serialization and deserialization of the object two aspects provide an example, The complete example is visible in the attachment: hessionrpc example (Eclipse Luna Works, requires Mavn support), and the API documentation for the Hessian with the source code: http://down.51cto.com/data/1973896.


An unpleasant hessian experience makes the understanding of RPC more profound, regardless of the framework, the serialization and deserialization of objects, the data transfer Protocol is the focus of implementation of RPC.

This article from "Mustang Red" blog, declined reprint!

Hessian RPC Samples and Hessian serialized object transfers based on HTTP requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.