Redis7_17 高阶篇 第八章 手写Redis的分布式锁(基础版)
import redis
import uuid
import time
class SimpleRedLock:
def __init__(self, connections):
# 连接列表,应该是三个或者更多的Redis连接
self.connections = connections
self.retry_count = 3
self.retry_delay = 2
self.lock_ttl = 10
def _generate_lock_key(self, resource):
# 生成唯一的锁名
return f"redlock:{resource}"
def _acquire_lock(self, connection, lock_key, lock_value, lock_ttl):
# 尝试在单个Redis实例上获取锁
return connection.set(lock_key, lock_value, ex=lock_ttl, nx=True)
def _release_lock(self, connection, lock_key, lock_value):
# 释放锁的模板方法,可以根据需要进行扩展
script = f"if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"
lock_key_b = bytes(lock_key, encoding='utf-8')
lock_value_b = bytes(lock_value, encoding='utf-8')
return connection.eval(script, 1, lock_key_b, lock_value_b)
def lock(self, resource):
# 获取锁的主函数
lock_key = self._generate_lock_key(resource)
lock_value = str(uuid.uuid4())
attempts = 0
while attempts < self.retry_count:
for conn in self.connections:
if self._acquire_lock(conn, lock_key, lock_value, self.lock_ttl):
# 如果在大多数节点上获取锁成功,则返回锁对象
return SimpleRedLockInstance(self, lock_key, lock_value, conn)
time.sleep(self.retry_delay)
attempts += 1
return False
class SimpleRedLockInstance:
def __init__(self, redlock, lock_key, lock_value, connection):
self.redlock = redlock
self.lock_key = lock_key
self.lock_value = lock_value
self.connection = connection
def unlock(self):
# 释放锁的方法
return self.redlock._release_lock(self.connection, self.lock_key, self.lock_value)
# 使用示例
if __name__ == "__main__":
# 假设有三个Redis连接
redis_connections = [redis.Redis(host=host, port=port) for host, port in [("localhost", 6379), ("localhost", 6380), ("localhost", 6381)]]
redlock = SimpleRedLock(redis_connections)
lock_instance = redlock.lock("my_resource")
if lock_instance:
try:
# 在这里执行需要锁保护的代码
print("Acquired lock. Doing some work...")
finally:
# 释放锁
lock_instance.unlock()
这个简化版本的Redis分布式锁实现了基本的锁定和解锁功能。它使用Redis SET命令的NX选项来确保只有一个客户端可以获得锁,并通过
评论已关闭