The use of serialization and deserialization of Jedis and Java objects

Source: Internet
Author: User

1. Jedis Version: Jedis-2.6.2.jar

Background: Now the system provides the Portal interface service, using JDBC to query the database directly, using the caching function provided by Jedis, with Redis in front of JDBC, first querying data from Redis, if there is no data in Redis, query from database. The result of the query is put into Redis, and the next time the interface is requested, the data in Redis is returned directly.

2. Use of serialization and deserialization

The data that the interface queries to is a list collection that is put into a redis by serializing the collection object into a string. Use to remove data from Redis by deserializing it into object usage.

3. Here are examples of applications for serialization and deserialization of Redis and Java objects

ImportJava.io.ByteArrayInputStream;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.io.UnsupportedEncodingException;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importcom.alibaba.druid.util.StringUtils;ImportRedis.clients.jedis.Jedis;ImportRedis.clients.jedis.JedisPool;ImportRedis.clients.jedis.JedisPoolConfig; Public Final classRedisutil {//Redis Server IP    Private StaticString ADDR = "192.168.7.182"; //the port number of the Redis    Private Static intPORT = 6379; //Access Password    Private StaticString AUTH = "admin"; //the maximum number of available connection instances, with a default value of 8;//If the assignment is-1, it is unrestricted, and if the pool is already assigned a maxactive Jedis instance, the state of the pool is exhausted (exhausted) at this time.     Private Static intMax_active = 1024; //controls the maximum number of Jedis instances in a pool that have an idle (idle) state, and the default value is 8.     Private Static intMax_idle = 200; //The maximum time to wait for an available connection, in milliseconds, and the default value is-1, which means that never times out. If the waiting time is exceeded, the jedisconnectionexception is thrown directly;    Private Static intMax_wait = 10000; Private Static intTIMEOUT = 10000; //whether validate operations are performed in advance when a Jedis instance is borrow, and if true, the resulting Jedis instances are available;    Private Static BooleanTest_on_borrow =true; Private StaticJedispool Jedispool =NULL; /*** Initializing Redis connection pool*/    Static {        Try{jedispoolconfig config=NewJedispoolconfig (); //config.setmaxactive (max_active);Config.setmaxidle (Max_idle); //config.setmaxwait (max_wait);Config.settestonborrow (Test_on_borrow); //using the Redis password//Jedispool = new Jedispool (config, ADDR, PORT, TIMEOUT, AUTH); //do not use the Redis passwordJedispool =NewJedispool (config, ADDR, PORT, TIMEOUT,NULL); } Catch(Exception e) {e.printstacktrace (); }    }        /*** Get Jedis instances *@return     */     Public synchronized StaticJedis Getjedis () {Try {            if(Jedispool! =NULL) {Jedis resource=Jedispool.getresource (); returnresource; } Else {                return NULL; }        } Catch(Exception e) {e.printstacktrace (); return NULL; }    }        /*** Release Jedis resources *@paramJedis*/     Public Static voidReturnresource (FinalJedis Jedis) {        if(Jedis! =NULL) {Jedispool.returnresource (Jedis); }    }        //object is serialized as a string     Public Staticstring objectserialiable (Object obj) {string Serstr=NULL; Try{bytearrayoutputstream Bytearrayoutputstream=NewBytearrayoutputstream (); ObjectOutputStream ObjectOutputStream=NewObjectOutputStream (Bytearrayoutputstream);                Objectoutputstream.writeobject (obj); Serstr= Bytearrayoutputstream.tostring ("Iso-8859-1"); Serstr= Java.net.URLEncoder.encode (Serstr, "UTF-8");              Objectoutputstream.close ();        Bytearrayoutputstream.close (); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                returnSerstr; }        //string deserialization to Object     Public StaticObject Objectdeserialization (String serstr) {Object NEWOBJ=NULL; Try{String Redstr= Java.net.URLDecoder.decode (Serstr, "UTF-8"); Bytearrayinputstream Bytearrayinputstream=NewBytearrayinputstream (Redstr.getbytes ("Iso-8859-1")); ObjectInputStream ObjectInputStream=NewObjectInputStream (Bytearrayinputstream); NEWOBJ=Objectinputstream.readobject ();              Objectinputstream.close ();        Bytearrayinputstream.close (); } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        returnNEWOBJ; }        //Test     Public Static voidMain (string[] args) {//Constructs a listlistNewArraylist(); HashMap<string, string> map =NewHashmap<string, string>(); Map.put ("Number", "Wangxiao"); Map.put ("Name", "Wang er");          List.add (map); HashMap<string, string> map2 =NewHashmap<string, string>(); Map2.put ("Number", "Zhang San"); Map2.put ("Name", "Zhangxiao");                List.add (MAP2); //serializing an object as a stringString Serstr =objectserialiable (list);                System.out.println (SERSTR); //Save serialized string in RedisRedisutil.getjedis (). Set ("List", SERSTR); //fetching the string from RedisString deserstr = Redisutil.getjedis (). Get ("list"); if(!Stringutils.isempty (DESERSTR)) {            //deserializes the extracted string into an objectlist) objectdeserialization (DESERSTR); if(delist!=NULL&& delist.size () >0){                 for(Map m:delist) {System.out.println (M.get ("Number") + "" "+m.get (" name "))); }            }        }            }}

4. Program Run Results

This is the string after the object is serialized
%c2%ac%c3%ad%00%05sr%00%13java.util.arraylistx%c2%81%c3%92%1d%c2%99%c3%87a%c2%9d%03%00%01i%00%04sizexp%00%00%0 0%02w%04%00%00%00%0asr%00%11java.util.hashmap%05%07%c3%9a%c3%81%c3%83%16%60%c3%91%03%00%02f%00%0aloadfactori%0 0%09thresholdxp%3f%40%00%00%00%00%00%0cw%08%00%00%00%10%00%00%00%02t%00%04namet%00%06%c3%a7%c2%8e%c2%8b%c3%a4% c2%ba%c2%8ct%00%06numbert%00%09%c3%a7%c2%8e%c2%8b%c3%a5%c2%b0%c2%8f%c3%a4%c2%ba%c2%8cxsq%00%7e%00%02%3f%40%00 %00%00%00%00%0cw%08%00%00%00%10%00%00%00%02q%00%7e%00%04t%00%09%c3%a5%c2%bc%c2%a0%c3%a5%c2%b0%c2%8f%c3%a4%c2% b8%c2%89q%00%7e%00%06t%00%06%c3%a5%c2%bc%c2%a0%c3%a4%c2%b8%c2%89xx
This is the output after deserializing the object through a string Wangxiao Wang Yizhang Zhangxiao

The use of serialization and deserialization of Jedis and Java objects

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.