Redis Serialization Pojo

Source: Internet
Author: User

There are many types of redis storage, but I personally think the best use is not a string storage type, but the hash storage type, if you use a Redis only to use only the string storage type, I personally feel that the features of Redis is completely not reflected.

Redis is a key-value database, but in my opinion he is not a simple key-value database, because Redis provides more data type storage formats than other NOSQL data of the same type. For example, if you need to use a NoSQL type of database as an application cache, I believe that memcached is more appropriate than Redis, but in reality many people use redis just to cache using a string type.

Redis has hash type value to store data format, do not know here, we have no idea of our traditional relational data storage format.

Actually, I've always wanted to make redis into a medium between application and traditional relational database, so as to reduce the IO of database in the environment of high load, and to realize the database persistence, and to realize the synchronization between asynchronous and traditional database better.

Hash

Common commands:

Hget,hset,hgetall and so on.

Application Scenarios:

Let's simply cite an example to describe the application scenario for a hash, such as storing a user information object data that contains the following information:

The user ID is the key to find, the stored value user object contains the name, age, birthday and other information, if the ordinary key/value structure to store, mainly has the following 2 kinds of storage methods:

The disadvantage of using the user ID as a lookup key to encapsulate other information as a serialized object is to increase the cost of serialization/deserialization and to retrieve the entire object when one of the information needs to be modified, and the modification operation requires concurrency protection. Introduce complex problems such as CAs.

The second method is how many members of this user information object will be saved into the number of key-value, with the user id+ the name of the corresponding property as a unique identifier to obtain the value of the corresponding property, although the cost of serialization and concurrency is omitted, but the user ID is repeated storage, if there is a large number of such data, The memory waste is still very considerable.

So the hash provided by Redis is a good solution to this problem, and the Redis hash is actually the internal stored value as a hashmap, and provides a direct access to the map member's interface, such as:

That is, the key is still the user ID, value is a map, the map key is a member of the property name, value is the property value, so that the data can be modified and accessed directly through its internal map key (Redis called internal map key field), This means that the corresponding attribute data can be manipulated by key (user ID) + field (attribute tag), without the need to store the data repeatedly and without the problem of serialization and concurrency modification control. A good solution to the problem.

     hash the table data stored in the corresponding database is the same, so we can easily cut into Redis, and the traditional database table data into the Redis hash data type. What I need to share with you here is if you quickly insert objects into Redis.

     Online A lot of information on the Pojo deposit to the Redis hash, but most of the operation is more cumbersome, here is said the cumbersome is the developer need to do more things is not the code cumbersome, I here with you to share a more simple and convenient way:

/** * * @Title: set* @Description: Save entity * @return Void (region + ": H:" + setkey ") key indicator. * @throws */@SuppressWarnings ({"Unchecked", "rawtypes"}) public void Save (v V) {map<k, v> Map = new Jacksonhashmapp ER (entityclass). Tohash (v); Redistemplate.boundhashops ((K) (Region + ": H:" + setkey (region)). Putall (map);

The format after storage is:

Get Data:

/** * * @Title: get* @Description: Get object information based on the key of the object in Redis I would like to see the entries () method, connection.hgetall* @return e* @throws */@Suppr Esswarnings ({"Unchecked", "rawtypes"}) public E get (String key) {map<k, v> Map = (map<k, v>) redistemplate.bo Undhashops ((K) (Region + ": H:" + key)). Entries (); return (E) new Jacksonhashmapper (Entityclass). Fromhash (map);}

The above is a single pojo of data stored in the acquisition, but if it is a large number of data, we will also just do the same way to get the collection of objects multiple times? The answer is no, because Redis has provided us with a better way to handle pipelined pipeline operations, which means that multiple data is returned uniformly.

/** * *  @Title: listconn*  @Description:  Pipeline Bulk Get Object collection   Incoming object key   Official offer method *  @return  List<E>*  @throws  */@SuppressWarnings ("unchecked") public list <e> listpipe (Final list<string> keys)  {list<object> result =  redistemplate.executepipelined (new rediscallback<list<object>> ()  {@Overridepublic  list<object> doinredis (redisconnection connection) throws dataaccessexception { for  (Int i = 0; i < keys.size ();  i++)  {byte[] key =  redistemplate.getstringserializer (). Serialize ((region +  ": H:" +keys.get (i))); Connection.hgetall (key);} Return null;}}); return  ((list<e>)  result);} Self-implemented method: Executeconn@suppresswarnings ("Unchecked") Public list<e> listconn (final List< String> keys)  {hashmapper<e, k, v> jhm =  (hashmapper<e, k, v>)  new JacksonHashMapper<E> ( Entityclass); List<object> result = redistemplate.executeconn (new rediscallback<map<byte[],  byte[]>> ()  {@Overridepublic  map<byte[], byte[]> doinredis ( Redisconnection connection) Throws dataaccessexception {map<byte[], byte[]> map  = new HashMap<byte[], byte[]> (;for ) (int i = 0; i  < keys.size ();  i++)  {byte[] key = redistemplate.getstringserializer (). Serialize ((region +  ": H:" +keys.get (i))); Connection.hgetall (key);} RETURN&NBSP;NULL;}},JHM);return  ((list<e>)  result);}

     The method above returns a result set, but I find that the serialized attribute in the returned result set is not deserialized completely causing the output to appear garbled, first look at the deserialization method provided by Springdataredis:

@SuppressWarnings ({  "Unchecked",  "Rawtypes" &NBSP;}) private list<object>  Deserializemixedresults (List<object> rawvalues, redisserializer valueserializer, Redisserializer hashkeyserializer, redisserializer hashvalueserializer)  {if  ( Rawvalues == null)  {return null;} List<object> values = new arraylist<object> ();for  (Object rawValue  : rawvalues)  {if  (rawvalue instanceof byte[] &&  Valueserializer != null)  {values.add (Valueserializer.deserialize ((byte[))  rawValue);}  else if  (rawvalue instanceof list)  {// lists are the only  potential collections of mixed values....values.add (DeserializeMixedResults (List)  rawvalue, valueserializer, hashkeyserializer, hashvalueserializer));}  else if  (RAWValue instanceof set && ! ((Set)  rawvalue). IsEmpty ())  {values.add (Deserializeset (Set)  rawvalue, valueserializer);}  else if  (rawvalue instanceof map && ! ( (map)  rawvalue. IsEmpty ()) &&  ((map)  rawvalue). values (). iterator (). Next ()   Instanceof byte[])  {values.add (serializationutils.deserialize (MAP)  rawValue,  Hashkeyserializer, hashvalueserializer));}  else {values.add (RawValue);}} Return values;} Serializationutils class: Public static  

     then look at the deserialization method after I modified:

@SuppressWarnings ({  "Unchecked",  "Rawtypes" &NBSP;}) private list<object>  Deserializemixedresults (list<object> rawvalues,redisserializer hashkeyserializer,  REDISSERIALIZER&NBSP;HASHVALUESERIALIZER,HASHMAPPER&LT;E,&NBSP;K,&NBSP;V&GT;&NBSP;JHM)  {if  ( Rawvalues == null)  {return null;} List<object> values = new arraylist<object> ();for  (Object rawValue  : rawvalues)  {Map<byte[], byte[]>  obj =  (map<byte[],  byte[]>)  rawValue; Map<k, v> map = new linkedhashmap<k, v> (Obj.size ());for  ( Map.entry<byte[], byte[]> entry : obj.entryset ())  {map.put (K)   Hashkeyserializer.deserialize ((Entry.getkey ())),  (V)  hashvalueserializer.deserialize ((Entry.getValue ())));} Values.add (Jhm.fromhash (map));} Return values;}

The above is my solution to deal with the results of the pipeline deserialization garbled. If there are any areas that you do not understand, please correct me. Thank you.

Redis Serialization Pojo

Related Article

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.