Several implementations of Redis lock

Source: Internet
Author: User
Tags redis sleep function
1. Redis Lock ClassificationRedis can be used in the lock command table is INCR, SETNX, SET 2. The first type of lock command incr

The idea is that the key does not exist, then the value of the key will be initialized to 0, and then perform the INCR operation to add one.
The other user then performs a INCR operation, and if the number returned is greater than 1, the lock is being used.

    1, client A requests the server to get key value of 1 to obtain the lock
    2, Client B also to request the server to get key value of 2 to get lock failed
    3, client a executes code completion, delete lock
    4, Client B Gets a value of 1 when it waits for a period of time to obtain the key to obtain the lock Success
    5, client B executes code completion, deletes the lock

    $redis->incr ($key);
    $redis->expire ($key, $ttl); Set build time to 1 seconds
3. The second type of lock Setnx

The idea of this lock is to set the key to value if the key does not exist
If key already exists, SETNX does not do any action

    1, client A requests the server to set the value of the key, if the success of the set to indicate the success of the lock
    2, Client B also to request the server to set the value of the key, if the return failure, then on behalf of Lock failed
    3, client a executes code completion, delete the lock
    4, Client B waits for a while to request the value of setting key, set success
    5, Client B execute code completion, delete lock

    $redis->setnx ($key, $value);
    $redis->expire ($key, $ttl);
4. The third type of lock set

The above two methods have a problem, you will find that all need to set the key expiration. So why do you want to set key expiration? If the request execution quits unexpectedly for some reason, causing the lock to be created but not removed, the lock will remain so that the cache is no longer updated. So we need to add an expiration time safekeeping to the lock.
But the use of Expire to set up is not atomic operation. So it is possible to ensure atomicity through transactions, but there are still some problems, so the official reference to the other, the use of the SET command itself has been starting from version 2.6.12 to include the ability to set expiration time.

    1, client A requests the server to set the value of the key, if the success of the set to indicate the success of the lock
    2, Client B also to request the server to set the value of the key, if the return failure, then on behalf of Lock failed
    3, client a executes code completion, delete the lock
    4, Client B waits for a while to request the value of the set key, set success
    5, Client B execute code completion, delete the lock

    $redis->set ($key, $value, Array (' NX ', ' ex ' => $ttl));  Ex represents seconds
5. Other issues

Although the above step has met our needs, but still have to consider other issues.
1, Redis found that the lock failed to do. Interrupt request or circular request.
2, the circular request, if there is a lock acquired, the other in to acquire the lock, it is not easy to grab the lock of the possibility.
3, the lock expires in advance, client A has not finished, and then client B get to the lock, this time client a executed, will not be in the lock to delete the lock of B. 6. Solutions

For Issue 1: Use circular request, loop request to get lock
For question 2: For the second question, when the loop request acquires the lock, add the sleep function and wait a few milliseconds to execute the loop
For question 3: The key that is stored when the lock is added is random. In this case, every time when the key is deleted to determine the value of the key stored in the same and whether they save the same

        do {  //For problem 1, use loop
            $timeout = ten;
            $roomid = 10001;
            $key = ' Room_lock ';
            $value = ' room_ '. $roomid;  Assign a random value to the problem 3
            $isLock = Redis::set ($key, $value, ' Ex ', $timeout, ' NX ');//ex sec
            if ($isLock) {
                if Redis:: Get ($key) = = $value) {  //Prevent early expiration, mistakenly delete other requests created by the lock
                    //Execute internal code
                    redis::d El ($key);
                    continue;//execution successfully deletes the key and jumps out of the loop
                }
            else {
                usleep (5000);//sleep, reduce the lock frequency, ease the redis pressure, for the problem 2
            }
        } while ( ! $isLock);
7. Another lock

The above lock completely satisfies the demand, but the official also provides a lock algorithm, here in PHP as an example

    $servers = [
        [' 127.0.0.1 ', 6379, 0.01],
        [' 127.0.0.1 ', 6389, 0.01],
        [' 127.0.0.1 ', 6399, 0.01],
    ];

    $redLock = new Redlock ($servers);

    Lock
    $lock = $redLock->lock (' My_resource_name ', 1000);

    Delete Lock
    $redLock->unlock ($lock)

The above is an official method of locking, which is the same as the general approach of the 6th, except that the official writing is more robust. So it can be invoked directly by the official provider of the written class method. The authorities provide a variety of languages on how to implement locks.

Original link: Dennis ' s blog

Official offers distributed Redis lock instructions
Phpreids Distributed Locks
Talk about the setnx of Redis
PHP implementation in five common usage scenarios of Redis

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.