Redis Implements distributed locks

Source: Internet
Author: User

  1. Normal way

    1. Look directly at the code

      1. package com.whereta.jedis;import org.springframework.stereotype.component;import  redis.clients.jedis.jedis;import redis.clients.jedis.jedispool;import javax.annotation.resource; import java.util.calendar;import java.util.date;import java.util.concurrent.timeunit;/** *  created by vincent on 15-10-14. */@Component ("Jedislock") public class  JedisLock {    public class CacheName {         public static final string add_bean_after_check_lock_key =   "Addbeanafterchecklock";    }     @Resource      private jedispool jedispool;    public void addbeanaftercheck ( Int userid)  {        Jedis jedis =  Jedispool.getresource ();          calendar calendar = calendar.getinstance ();         calendar.set (calendar.millisecond, 0);         Date calendartime = calendar.gettime ();         long  time = calendartime.gettime ();         //with a user ID of key, Different users call the same method without locking         string key = cachename.add_bean_ after_check_lock_key +  ":"  + userid;        try  {            if  (jedis !=  NULL)  {                 Long lock = jedis.setnx (key, time +  "");                 while  (lock == 0)  {                     timeunit.milliseconds.sleep (50);                      lock = jedis.setnx (key, time +  "");                 }                 //Set timeout time                  jedis.expire (key, 3);             }            // Own business logic processing         } catch  (exception e)  {      &nbSp;      throw new runtimeexception (e);         } finally {             if  (jedis != null)  {                 jedis.del (Key);                 jedis.close ();             }        }    }}
    2. In the example, the user ID is key locking: When different users access the method, they do not reject the wait

    3. The implementation of the lock mechanism takes advantage of the Redis Setnx method: If a key exists in the database, it does not store the data and returns 0

    4. Redis's approach is thread-safe and can be used with confidence

  2. AOP approach

    1. Sample code

      1. package com.whereta.jedis;import org.aspectj.lang.proceedingjoinpoint;import  org.aspectj.lang.annotation.around;import org.aspectj.lang.annotation.aspect;import  org.springframework.stereotype.component;import redis.clients.jedis.jedis;import  Redis.clients.jedis.jedispool;import javax.annotation.resource;import java.util.calendar;import  java.util.date;import java.util.concurrent.timeunit;/** * created by vincent  on 15-10-14. */@Aspect @componentpublic class jedislockaop {      @Resource     private JedisPool jedisPool;     @Around (" Execution (Public * com.heli.core.pay.soaservice.impl.*.* (..)) ")     PUBLIC OBJECT SERVICEAOP (Proceedingjoinpoint point)  {         object proceed = null;      & NBsp; jedis jedis = jedispool.getresource ();         calendar calendar = calendar.getinstance ();         calendar.set (calendar.millisecond, 0);        date  Calendartime = calendar.gettime ();         long time  = calendartime.gettime ();         //request parameter Array          object[] args = point.getargs ();         //key can be customized         String key =  jedislock.cachename.add_bean_after_check_lock_key +  ":"  + args[0];         try {            if   (Jedis != null)  {                long  Lock = jedis.setnx (key, time +  "");                 while  (lock == 0)  {                      TimeUnit.MILLISECONDS.sleep (;             )        lock = jedis.setnx (key, time +  "");                 }                 //Set timeout time                  jedis.expire (key, 3);             }            //User Business Processing             proceed = point.proceed ();             return proceed;         } catch  (throwable throwable)  {             throw new runtimeexception (Throwable);         } finally {             if  (jedis != null)  {                 jedis.del (Key);                 jedis.close ();            &nbSP;}         }    }}
    2. Wrapping method using Spring AOP

    3. Specific key values can be customized to include, for example: IP, TIME, etc.


Redis Implements distributed locks

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.