Redis实现分布式锁代码
时间: 2024-04-08 22:08:12 浏览: 94
以下是使用Redis实现分布式锁的示例代码,使用了setnx和expire命令:
```
import redis
class RedisLock:
def __init__(self, redis_client, key, expire=60, wait_timeout=10):
self.redis_client = redis_client
self.key = key
self.expire = expire
self.wait_timeout = wait_timeout
self.locked = False
def acquire(self):
while not self.locked:
self.locked = self.redis_client.setnx(self.key, 1)
if self.locked:
self.redis_client.expire(self.key, self.expire)
return True
else:
time.sleep(0.1)
self.wait_timeout -= 0.1
if self.wait_timeout <= 0:
return False
def release(self):
if self.locked:
self.redis_client.delete(self.key)
self.locked = False
```
使用示例:
```
import redis
redis_client = redis.Redis(host='localhost', port=6379, db=0)
lock = RedisLock(redis_client, 'my_lock_key', expire=60, wait_timeout=10)
if lock.acquire():
try:
# 临界区代码
pass
finally:
lock.release()
else:
# 获取锁失败,处理逻辑
pass
```
阅读全文