原始问题:
怎么写一个分布式锁
要写一个分布式锁,可以使用Redis或Zookeeper等分布式存储系统。以下是一个使用Redis实现的简单示例:
- 安装Redis库:在Python中,可以使用
redis-py库来操作Redis。通过pip install redis命令进行安装。 - 编写分布式锁代码:
import time
import uuid
import redis
class DistributedLock:
def __init__(self, key, timeout=10, expire=60):
self.key = key
self.timeout = timeout
self.expire = expire
self.conn = redis.StrictRedis(host='localhost', port=6379, db=0)
self.lock_id = str(uuid.uuid4())
def acquire(self):
while True:
if self.conn.set(self.key, self.lock_id, ex=self.timeout, nx=True):
return True
time.sleep(0.1)
def release(self):
script = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
self.conn.eval(script, 1, self.key, self.lock_id)
# 使用示例
lock = DistributedLock('my_lock')
if lock.acquire():
try:
# 执行需要同步的代码
pass
finally:
lock.release()在这个示例中,我们创建了一个DistributedLock类,它有两个主要方法:acquire和release。acquire方法尝试获取锁,如果成功则返回True,否则等待一段时间后重试。release方法用于释放锁。
Prev:欢迎有意向的来考察文案