How to Use redis to implement distributed locks and redis to implement distributed locks

Source: Internet
Author: User

How to Use redis to implement distributed locks and redis to implement distributed locks
Introduction

Redis, as a powerful key/value database, can also be used to implement lightweight distributed locks.


1. Implementation solution 1

The earliest official code provided an implementation on the SETNX command page:

acquire lock: SETNX lock.foo <current Unix time + lock timeout + 1>
release lock: DEL lock.foo
acquire lock when time expired: GETSET lock.foo <current Unix timestamp + lock timeout + 1>


However, there is a vulnerability in this solution, that is, the DEL command used by release lock does not support cas deletion (delete if current value equals old value). Thus, a problem occurs when race condition is ignored:

A client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.


2. Implementation solution 2

The SETNX command page officially introduced a new solution: SET command + Lua script:

Starting with Redis 2.6.12 it is possible to create a much simpler locking primitive using the SET command to acquire the lock, and a simple Lua script to release the lock. the pattern is wrongly ented in the SET command page.

The old SETNX based pattern is already ented below for historical reasons.


This solution has two optimizations:

(1) The SET command can SET the key expiration time: SET key value [EX seconds] [PX milliseconds] [NX | XX]

The lock will be auto-released after the expire time is reached.


(2) Use the Lua script to delete cas (see the SET command page for details)

It is possible to make this system more robust modifying the unlock schema as follows:

  • Instead of setting a fixed string, set a non-guessable large random string, called token.
  • Instead of releasing the lock with DEL, send a script that only removes the key if the value matches.



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.