Home  >  Article  >  Database  >  How to implement redis distributed lock in python

How to implement redis distributed lock in python

王林
王林forward
2023-06-03 18:22:361481browse

 1 import time 2 import redis 3 from redis.exceptions import WatchError 4  5  6 class RedisUtil(): 7     def __init__(self): 8         self.redis = redis.Redis(host="redis账户url", 9                                  port=6379,10                                  password="你的redis密码",11                                  decode_responses=True)12         self.online_set_name = "palm_online_devices"13 14     # 获取锁15     def acquire_lock(self, key, val, acquire_time=60, time_out=60):16         start_time = time.time()17         # 阻塞等待,轮询去获取锁,获取不到,轮询等待,直到拿到锁或者超时18         while True:19             if time.time() - start_time > acquire_time:20                 return False21             # 用setnx实现分布式锁,当key存在时候,setnx不做任何动作,如果key不存在,将value值设置为val22             # 如果 SETNX 返回1,说明该进程获得锁,SETNX将键 lock.foo 的值设置为锁的超时时间(当前时间 + 锁的有效时间)。23             # 如果 SETNX 返回0,说明其他进程已经获得了锁,进程不能进入临界区。进程可以在一个循环中不断地尝试 SETNX 操作,以获得锁24             if self.redis.setnx(name=key, value=val):25                 # 设置key的时长为60秒,如果超过60秒,key销毁26                 self.redis.expire(key, time_out)27                 return True28 29     # 释放锁30     def release_lock(self, key, val):31         pip = self.redis.pipeline(True)32         while True:33             try:34                 pip.watch(key)35                 lock_value = self.redis.get(key)36                 if not lock_value:37                     return True38                 if lock_value == val:39                     pip.multi()40                     pip.delete(key)41                     pip.execute()42                     return True43                 pip.unwatch()44                 break45             except WatchError:46                 pass47         return False

What python can do

Python is a programming language with many built-in effective tools. Python can do almost anything. The language is easy to understand, easy to get started, and powerful in many fields. They all have a wide range of applications, such as the most popular big data analysis, artificial intelligence, web development, etc.

The above is the detailed content of How to implement redis distributed lock in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete