示例1:
import redis_lock
import redis
import time
from multiprocessing import Process
conn = redis.Redis(host='127.0.0.1', port=6379, decode_responses=True, db=3)
class TestLock(object):
def __init__(self):
self.lock = redis_lock.Lock(conn, "name-of-the-lock")
# if lock.acquire(blocking=False):
# print("Got the lock.")
# lock.release()
# else:
# print("Someone else has the lock.")
def get_lock(self):
print(self.lock, "xxxxxxxxxxxxxxxxxxxxx")
def set_lock(self):
if self.lock.acquire(blocking=True):
print("Got the lock.")
# 获取lock,执行业务处理
time.sleep(3)
#self.lock.release()
return True
else:
print("someon else has the lock")
return False
def task():
test_lock = TestLock()
test_lock.get_lock()
#print(f"{test_lock.lock}-----------------test_lock")
# 设置redis锁,操作redis
test_lock.set_lock()
# if test_lock.lock.acquire(blocking=False):
# print("Got the lock.")
# # 获取lock,执行业务处理
# time.sleep(3)
# test_lock.release()
# else:
# print("someon else has the lock")
if __name__ == '__main__':
for i in range(10):
p = Process(target=task)
p.start()
time.sleep(1)
# print(f"{lock}-----------------lock")
# lock = redis_lock.Lock(conn, "name-of-the-lock")
# if lock.acquire(blocking=False):
# print("Got the lock.")
# # 获取lock,执行业务处理
# time.sleep(3)
# lock.release()
# print("release the lock.")
# else:
# print("someon else has the lock")
# #lock.release()
redis锁查看
redis-cli.exe -h 127.0.0.1 -p 6379
SELECT 3
keys *