Redis Application Analytics

Source: Internet
Author: User

official website : Http://redis.io

definition : persistent High-performance Key-value in -memory Database

Application Scenarios : Data caching, chat systems, traffic statistics, Message Queuing, distributed locks, and more

Advantage Comparison:

• Lightweight: Redis is very lightweight (source only 1.5M), personally I prefer small and light things, for some as far as possible to want the perfect and huge things I am very disgusted, some things as far as possible to pursue the perfect but ignore the most essential things or the original product design and persistence: red is provides very good persistence support to ensure data integrity and high performance: Redis is a memory-based middleware, memory type means better performance (actual test, single-threaded intranet environment can be completed 10,000 times/s write operation), the characteristics of the inter-view so that he has a good distribution of support · Rich data types and commands: Redis has a string, List, Hash, Set, sortset 5 data types and rich operational commands that enable Redis to be applied to multiple scenarios in addition to basic functionality • Rich Client language support • Easy to use the implementation of a distributed lock for Redis applications:Principle: The distributed lock mainly applies the Redis's setnx command feature, SETNX key value, sets the value of key to value, and does not handle when key already exists, we use the attribute which cannot be assigned simultaneously to implement the effect code of the lock: Get the Lock
1 /**2 * Get distributed lock Dlock3      * @paramkey Lock Flag4      * @paramHolder lock holder (usually UUID, uniquely identifies the holder of the current lock)5      * @paramtimeout to get lock time-out milliseconds6      * @return7      */8      Public Static BooleanGetdlock (string key, string holder,LongTimeout) {9Jedis Jedis =Drjedis.getjedispool ();Ten         //to set the time-out for lock acquisition One         LongEnd = System.currenttimemillis () +timeout; A          while(System.currenttimemillis () <end) { -             if(JEDIS.SETNX (Lock_prefix + key, Holder) = = 1)return true; -             Try { theThread.Sleep (10); -}Catch(interruptedexception e) { -Log.error ("Get Dlock exception", e); -                 return false; +             } -         } +Log.error ("Get Dlock timeout"); A         return false; at}
View Code

This method means that if setnx succeeds, it means that no other thread currently holds the key, acquires the lock, and prevents the other thread from acquiring the lock again, and if the fetch fails, attempts to regain it within the timeout time range, otherwise the fetch lock fails

Release Lock: Release the lock to remove the key operation so that other threads can setnx

1 /**2 * Release Lock3      * @paramkey Lock Flag4      * @paramHolder lock holder (usually UUID, uniquely identifies the holder of the current lock)5      */6      Public Static voidReleasedlock (string key, string holder) {7Jedis Jedis =Drjedis.getjedispool ();8          while(true){9             Try {TenJedis.watch (Lock_prefix +key); OneString value = jedis.get (Lock_prefix +key); A                 if(Value! =NULL&& value.equals (Holder)) {//ensure that the current holder's lock is released -Transaction Tran =Jedis.multi (); -Jedis.del (Lock_prefix +key); the tran.exec (); -                 } - Jedis.unwatch (); -                  Break; +}Catch(Exception e) { -Log.error ("Release lock Exception", e); +                  Break; A             } at         } -}
View Code

This method represents the release lock, which guarantees the lock operation at the same time through the transaction

The two MQ implementations of REDIS applications:

Principle: MQ is based on the Redis list data type implementation, the right side of the queue, the left side of the first-in first-out feature

Production Message Code

1 /**2 * Production Message3      * @paramKey Message Key4      * @paramMessage body, supports mass production messages, produces at least one message5      */6      Public Static voidproduct (String key, string ... message) {7         Try{8Drjedis.getjedispool (). Rpush (Mq_prefix +key, message);9}Catch(Exception e) {TenLog.error ("Jedis product Message", e); One         } A}
View Code

Rpush push in queue from right end

Consumer News:

1 /**2 * Consumer News3      * @paramKey Message Key4      * @paramCustomer message consumption business, need to implement customer interface customer method for business processing5      */6      Public Static voidCustomer (String key, Icustomer customer) {7         Try{8Jedis Jedis =Drjedis.getjedispool ();9              while(true){Ten                 //Popup Message Onelist<string> messages = Jedis.blpop (0, Mq_prefix +key); A                 if(Messages.size () >= 2){ -                     Try { -                         //Consumer News theCustomer.customer (messages.get (0), Messages.get (1)); -}Catch(rollbackexception e) { -                         //message consumption failed to re-produce the message, and there is a left-hand press queue, to ensure that the next time the first to be consumed -Jedis.lpush (messages.get (0), Messages.get (1)); +                     } -                 } +             } A}Catch(Exception e) { atLog.error ("Jedis Customer Message", e); -         } -}
View Code

Blpop pops the message from the left, and if the queue is empty it blocks the message waiting, and this method simulates the listener using a while (true) infinite loop to facilitate timely consumption of messages, Icustomer define the specific consumption business, and throws the Rollbackexception exception indicates, the message consumes the failure, needs to rollback, then pushes back from the left to the queue, guarantees the next time to be consumed by the first

1 /** 2 * Created by Xiao on 2016/5/20. 3 */ 4  Public Interface Icustomer {56     void throws rollbackexception; 7 8 }
View Code

The business of consuming messages needs to implement Icustomer's customer approach, consuming messages

1 /**2 * Rollback Exception3  */4  Public classRollbackexceptionextendsException {5 6      Publicrollbackexception (String message) {7         Super(message);8     }9 Ten      Publicrollbackexception () { One         Super(); A     } -  -      Publicrollbackexception (String message, throwable cause) { the         Super(message, cause); -     } -  -      Publicrollbackexception (Throwable cause) { +         Super(cause); -     } +  A     protectedRollbackexception (String message, throwable cause,BooleanEnablesuppression,Booleanwritablestacktrace) { at         Super(message, cause, enablesuppression, writablestacktrace); -     } -}
View Code

Redis Application Analytics

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.