Redis如何实现分布式锁

其中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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值