其中KEY[1]表示lock_key,ARGV[1]表示当前客户端的唯一标识,这两个值是我们在执行lua脚本时作为参数传入的。下面我们来看一下完整的代码实现。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import redis
import traceback
import uuid
import time
class Inventory(object):
def init(self):
pool = redis.ConnectionPool(host=‘localhost’, port=6379, decode_responses=True)
client = redis.StrictRedis(connection_pool=pool, max_connections=20)
self.client=client
self.uuid=str(uuid.uuid1())
print(self.uuid)
self.key=“lock_key”
self.inventory_key=“inventory”
def unlock(self):
unlock_script=""
“if redis.call(“get”,KEYS[1]) == ARGV[1] then”
" return redis.call(“del”,KEYS[1])"
“else”
" return 0 "
“end”
try:
unlock_cmd=self.client.register_script(unlock_script)
result=unlock_cmd(keys=[self.key],args=[self.uuid])
if result==1:
print(“释放成功”)
else:
print(“释放出错”)
except:
print(traceback.format_exc())
def lock(self):
try:
while True:
result=self.client.set(self.key,self.uuid,px=100,nx=True)
print(result)
if result==1:
break
print("sleep 1s")
time.sleep(1)
print("加锁成功")
return True
except:
print(traceback.format_exc())
def inventory(self):
if self.lock():
print("库存扣减")
self.client.decr(self.inventory_key)
print("扣减完成")
self.unlock()
inv=Inventory()
inv.inventory()
mosfet驱动芯片https://www.zg886.cn