关于Redis的SETNX 实现的分布式锁问题

Pisces_Aries 2018-04-25 11:08:33
If SETNX returns 1 the client acquired the lock, setting the lock.foo key to the Unix time at which the lock should no longer be considered valid. The client will later use DEL lock.foo in order to release the lock.

If SETNX returns 0 the key is already locked by some other client. We can either return to the caller if it's a non blocking lock, or enter a loop retrying to hold the lock until we succeed or some kind of timeout expires.

redis.io 关于setnx 有这么一段 描述, 其中他说 If SETNX returns 1 the client acquired the lock, setting the lock.foo key to the Unix time at which the lock should no longer be considered valid. 有木有大佬解释一下这句话到底是什么意思,是说当客户端获得了锁,这个命令的过期时间就不再有效了
...全文
1836 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
深山猿 2019-04-20
  • 打赏
  • 举报
回复
释放锁有两种方式,如果使用锁正确结束,则通过del释放锁;还有一种情况是连接断开了,线程挂了,没有办法释放锁,此时另一线程来请求该锁就会无法获取,进入死锁状态。为了避免上面问题,时间用来说明锁的有效时间,过了时间,原本拥有线程的锁即使没有释放,别的线程会释放并争抢该锁。
  • 打赏
  • 举报
回复
If SETNX returns 1 the client acquired the lock, setting the lock.foo key to the Unix time at which the lock should no longer be considered valid. The client will later use DEL lock.foo in order to release the lock. 如果SETNX返回1(代表)客户端已经获得该锁,设置 lock.foo键为某个代表之后锁失效的unix时间。客户之后可以用 DEL lock.foo释放该锁。 意思应该是获得锁的客户端可以设置一个锁失效时间,在此时间之前锁一直有效,但是客户端也可以用 DEL lock.foo提前释放锁。 unix时间是1970-01-01 0点开始的秒计数。

2,498

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 数据库相关
社区管理员
  • 数据库相关社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧