A use case for a Java serialization object

Source: Internet
Author: User
Tags http post object serialization


The serialization section ofeffective Javahas the following explanation for the serialization of Java:

Object serialization API, which provides a framework for encoding an object into a byte stream (serializing) and rebuilding an object (deserializing) from a byte stream encoding. Once an object has been serialized, its encoding can be passed from one running JVM to another, or stored on disk for later deserialization (such as the persistence of a Tomcat session). Serialization technology provides a standard line-level object representation for remote communication , as well as a standard persistent data format for the JavaBeans component structure.


About the Java serialization, read a lot of information, has not fully understood the inside of the secret, just recently reread effective Java, and then add these two days encounter a demand, can very good interpretation of serialization, so in this side summary under.


Requirements: The system wrote a memory cache, and then each node in the cluster to maintain their own memory cache (PS: Someone is sure to say Mrs. Eastby, how not memcached or Redis, FA, leader requirements ...), This memory cache is actually a map-based, Key=string,value=object object. The cache needs to provide a way to refresh a single kv in a map of all nodes in the cluster.


Analysis of the above requirements, the map value is the object, this object is not a general string, and is exactly a true JavaBean object, refresh, you need to send a new bean to each node, Each node then operates the map in memory. In this way, there is a prototype, each node needs to provide an HTTP interface, refresh, the Bean object to the HTTP, so that the effective Java as described above, to provide a standard line-level object representation for remote communication, the object The Bean is post to the HTTP interface as stream, and after the HTTP interface is connected to the stream, the stream is deserialized into a bean object.


The code is implemented as follows:

JavaBean is not listed, is a very pure bean class, except that the class must be serialized (about the advanced step of serialization refer to effective Java), the author here only implements Serializable To meet your needs.


HTTP POST Tool class:

Import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.objectoutputstream;import Java.io.outputstream;import Java.net.httpurlconnection;import Java.net.URL; Import Org.apache.commons.io.ioutils;import Org.apache.commons.lang.stringutils;import org.apache.log4j.Logger;/* * * Http Request Access Tool class * * @author Will_awoke * @version 2014-6-26 * @see httpaccessutil * @since */public class Httpaccessutil       {/** * log * */private static Logger log = Logger.getlogger (Httpaccessutil.class); /** * Take post to commit the serialized object </br> * See also: Java.io.objectinputstream/objectoutputstream * @param request URL Request Address * @param conntimeoutmills Set Connection host timeout in milliseconds * @param readtimeoutmills set read data timeout from host, in milliseconds * @param seriali Zedobject the serialized Object Object * * @return Remotehttp Returns the result */public static string Httppostserialobject (String re Questurl, int conntimeoutmills, int ReadtimeoUtmills, Object serializedobject) throws Exception {httpurlconnection httpurlconn = null;        InputStream inputstream = null;        InputStreamReader inputstreamreader = null;        BufferedReader bufferedreader = null;        ObjectOutputStream oos = null;        StringBuffer buffer = new StringBuffer ();            try {URL url = new URL (requesturl);            Httpurlconn = (httpurlconnection) url.openconnection (); Set Content_type=serialized_object//If this key is not set, when the serialized object is transferred, the Web Service may throw java.io.EOFException HTTP when the default is not this type            Urlconn.setrequestproperty ("Content-type", "Application/x-java-serialized-object");            Httpurlconn.setconnecttimeout (Conntimeoutmills);            Httpurlconn.setreadtimeout (Readtimeoutmills);            Sets whether to output to httpurlconn, because it is a POST request, the parameter is placed inside the HTTP body, so it needs to be set to True, False httpurlconn.setdooutput (TRUE) by default;     Sets whether to read from Httpurlconn, which by default is True Httpurlconn.setdoinput (true);       Do not use cache httpurlconn.setusecaches (false);            Set the request mode, the default is Get Httpurlconn.setrequestmethod ("POST");            Httpurlconn.connect ();                   if (serializedobject! = null) {///here Getoutputstream will implicitly connect, i.e., like calling the Connect () method above, It is also possible to not call the above connect () in development, but it is advisable to explicitly call//write Object (Impl Serializable) using Objectoutputstrea                M oos = new ObjectOutputStream (Httpurlconn.getoutputstream ());                Oos.writeobject (Serializedobject);                Oos.flush (); OutputStream is not a network stream, at best a string stream, the content written to it will not be sent to the network immediately,//But in the memory buffer, when the OutputStream stream is closed, generate HTTP text based on the input.            So the close here is a must oos.close ();            }//Convert the returned input stream into a string//either the post or the Get,http request is actually sent out until the function of HttpURLConnection getInputStream () InputStream = Httpurlconn.getinputstream ();//Note that the code snippet that actually sends the request is here InputStreamReader = new INPUtstreamreader (InputStream, "UTF-8");            BufferedReader = new BufferedReader (InputStreamReader);            String str = NULL;            while ((str = bufferedreader.readline ()) = null) {buffer.append (str);            }} catch (Exception e) {log.error (Requesturl + "error", e);        Throw e;                } finally {try {ioutils.closequietly (BufferedReader);                ioutils.closequietly (InputStreamReader);                ioutils.closequietly (InputStream);                ioutils.closequietly (Oos);                if (httpurlconn! = null) {httpurlconn.disconnect ();            }} catch (Exception e) {log.error (e);    }} return buffer.tostring (); }}

Here is a bit to highlight, httpconnect of the Content-type must be set toApplication/x-java-serialized-object, or the HTTP interface will appear when the stream is receivedjava.io.EOFException。 Also: The output object is using the ObjectOutputStream WriteObject method.


The HTTP interface receives the stream and deserializes it into an object bean:

The read object from stream deserializes the stream to generate the object ObjectInputStream ois = new ObjectInputStream (Req.getinputstream ());// HttpServletRequest Req Objects Object value = Ois.readobject ();

The back is the replace map, no longer repeat.


In short, this requirement is a further understanding of the role of Java serialization:)



A use case for a Java serialization object

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.