Redis simple distributed lock

Why do you need a lock?

Locks restrict independent processes to occupy the same resource at the same time. The resource can be a database record, (row-level lock corresponds to a record, and table-level lock corresponds to a type of record.).

We usually want this restriction for two purposes:

  • Security (safety)
    through the lock limit, the concurrent operation of the resource is released, different processes can only operate the resource in sequence. A very practical example is a database transaction
  • Effectiveness
    locks limit different processes from occupying computing resources.

Redis provides a command that can achieve the purpose of locking

set key value [EX seconds] [PX milliseconds] [NX|XX]
EX seconds:设置失效时长,单位秒
PX milliseconds:设置失效时长,单位毫秒
NX:key不存在时设置value,成功返回OK,失败返回(nil)
XX:key存在时设置value,成功返回OK,失败返回(nil)

案例:设置name=p7+,失效时长100s,不存在时设置
1.1.1.1:6379> set name p7+ ex 100 nx
OK
1.1.1.1:6379> get name
"p7+"
1.1.1.1:6379> ttl name
(integer) 94


This shows that this is just a simple distributed lock, which will only go wrong in extreme cases, so if you are in a situation where you only need to ensure that the data is reliable most of the time, and it does not matter if there is a problem, then use a single node with confidence Redis or master-slave cluster to lock it.
If you have high requirements for data reliability, then please understand other solutions to implement distributed locks. For example, "complex" distributed locks based on ZK, etcd.

Published 200 original articles · praised 13 · 40,000+ views

Guess you like

Origin blog.csdn.net/u013919153/article/details/105617128