Implementation of Redis and zookeeper distributed locks

Source: Internet
Author: User
Tags aop redis throwable zookeeper tomcat
1. Distributed lock

Distributed locks are generally used in distributed systems or in multiple applications to control the execution of the same task or the order in which the task is executed. In the project, multiple Tomcat applications were deployed, and when a timed task was executed, it was possible to perform the same task multiple times, and we could use a distributed lock to ensure that only one Tomcat application performed timed tasks at the same time. 2. Implementation of distributed locks using Redis's setnx () and expire () using Redis's Getset () Use the Zookeeper node node to create a temporary sequence of nodes 3 using zookeeper . Use Redis's setnx () and expire () to implement distributed locks

SETNX (Key,value) If key does not exist, set to the value of the current key, or return directly if key exists.
expire () to set the time-out period

Define the Annotation class:

@Target ({Elementtype.method})
@Retention (retentionpolicy.runtime) public
@interface lockable{
    // Redis cache key
    String key ();
    Redis caches data in key
    String value () default "";
    Expiration time (seconds), default is one minute
    long expire () defaults;
}

Timer task Add Note @lockable:

@Lockable (key = "distributedlock:dealexpirerecords") public
 void Dealexpirerecords () {
 }

The

Defines an AOP facet lockaspect, using @around to process all annotations as @lockable, confirming that the annotation is used on the method through the connection point, obtaining the annotation information by means of the method, using Setifabsent to determine whether to obtain the distributed lock, If a distributed lock is not acquired, it is returned directly, if a distributed lock is obtained, the expiration time is set through expire and the specified method is called.

@Component @Slf4j @Aspect public class lockaspect {@Autowired private redistemplate redistemplate; @Around ("@annotation (com.records.aop.Lockable)") Public Object Distributelock (Proceedingjoinpoint pjp) {Ob

        Ject resultobject = null;
        Confirm that this annotation is used on the method Signature Signature = Pjp.getsignature (); if (! (
            Signature instanceof methodsignature) {log.error ("lockable is Method annotation!");
        return resultobject;
        } methodsignature methodsignature = (methodsignature) signature;

        Method Targetmethod = Methodsignature.getmethod ();
        Get annotation information lockable lockable = targetmethod.getannotation (Lockable.class);
        String key = Lockable.key ();
        String value = Lockable.value ();

        Long expire = Lockable.expire (); A distributed lock that sets this value and returns true if there is no this key, and returns False if there is a Boolean result = Redistemplate.boundvalueops (key). Setifabsent (value)
        ;
       if (!result) {     Other programs have acquired the distributed lock return resultobject;

        }//Set expiration time, default one minute Redistemplate.boundvalueops (key). Expire (expire, timeunit.seconds); try {resultobject = Pjp.proceed ();//Call corresponding method execution} catch (Throwable throwable) {THROWABLE.P
        Rintstacktrace ();
    } return resultobject;
 }
}
4. Using Redis's Getset () to implement distributed locks

This method causes the Redistemplate.boundvalueops (key). Getandset (value) method, if returned empty, to obtain a distributed lock, or if the return is not NULL, indicates that the distributed lock has been consumed by another program by 5. Create node with zookeeper

Using zookeeper to create node nodes, if the creation of the node succeeds, it means that the distributed lock is acquired, if the creation of the node fails, it means that this distributed lock is already occupied by other programs (multiple programs create one node at the same time, only one can be created successfully) 6. Creating a temporary sequence node using zookeeper

Using zookeeper to create a temporary sequence node to implement distributed locks, suitable for sequential execution of the program, the general idea is to create a temporary sequence node, find the smallest sequence node, obtain a distributed lock, the program after the completion of the sequence node disappears, watch to monitor the change of the node, Find the smallest sequence node from the remaining nodes, get the distributed lock, perform the appropriate processing, and so on ...



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.