提交 39d863eb 编写于 作者: Q qiurunze

lua分布式锁

上级 8aa5ce85
......@@ -66,6 +66,7 @@
| 024 |如何进行分库分表 |[解决思路](/docs/mysql-master-slave.md) |
| 025 |秒杀类似场景sql的写法注意事项有哪些?|[解决思路](/docs/mysql-master-slave.md) |
| 026 |如何利用lua脚本进行操作限流与分布式锁(可保证原子性)?|[解决思路](/docs/redis-good.md) |
| 027 |如何利用lua脚本进行分布式锁操作?|[解决思路](/docs/redis-good.md) |
#### [分布式系统发展历程(已更新)](/docs/fenbushi.md)
#### [分布式系统](/docs/redis-code.md)
......
......@@ -155,6 +155,8 @@
最后第二个窗口的运行结果是Busy, 可以通过script kill命令终止正在执行的脚本
如果当前执行的lua脚本对redis的数据进行了修改,比如(set)操作,那么script kill命令没办法终止脚本的运行,
因为要保证lua脚本的原子性。如果执行一部分终止了,就违背了这一个原则
在这种情况下,只能通过 shutdown nosave命令强行终止
在这种情况下,只能通过 shutdown nosave命令强行终止
**Redis(2.6以后)--lua分布式锁**
![整体流程](https://raw.githubusercontent.com/qiurunze123/imageall/master/lualock.png)
package com.geekq.miaosha.redis.redismanager.lua;
public class RedisLuaLock {
}
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by qiurunze.
--- DateTime: 2018/12/22 18:20
---
--- 释放锁
if redis.call('get',KEY[1] == ARGV[1]) then
return redis.call('del',KEY[1])
else
return 0
end
--- 加锁
local key = KEY[1]
local content = KEY[2]
local ttl = AVG[1]
local lockSet = redis.call('setnx',key,content)
if lockSet==1 then
redis.call('pexpire',key,ttl)
else
local value = redis.call('get',key)
if value==content then
lockSet=1
redis.call('pexpire',key,ttl)
end
end
return lockSet
\ No newline at end of file
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by qiurunze.
--- DateTime: 2018/12/22 16:33
---
---
local key = KEY[1]
local content = KEY[2]
local ttl = AVG[1]
local lockSet = redis.call('setnx',key,content)
if lockSet==1 then
redis.call('pexpire',key,ttl)
else
local value = redis.call('get',key)
if value==content then
lockSet=1
redis.call('pexpire',key,ttl)
end
end
return lockSet
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册