redis锁防止重复提交
时间: 2023-09-24 16:13:27 浏览: 81
防止重复提交
可以使用Redis的分布式锁来防止重复提交。下面是一个基本的示例代码:
```python
import redis
import time
# 创建Redis连接
redis_client = redis.Redis(host='localhost', port=6379, db=0)
def acquire_lock(lock_name, acquire_timeout=10, lock_timeout=10):
# 生成唯一的锁标识符
identifier = str(time.time())
end_time = time.time() + acquire_timeout
while time.time() < end_time:
# 尝试获取锁
if redis_client.setnx(lock_name, identifier):
# 设置锁的超时时间,避免死锁
redis_client.expire(lock_name, lock_timeout)
return identifier
time.sleep(0.001) # 等待一段时间后重试
return None
def release_lock(lock_name, identifier):
with redis_client.pipeline() as pipe:
while True:
try:
# 监视锁,确保在删除之前没有其他线程修改了它
pipe.watch(lock_name)
if pipe.get(lock_name).decode() == identifier:
# 释放锁
pipe.multi()
pipe.delete(lock_name)
pipe.execute()
return True
# 其他线程修改了锁,取消监视并重试
pipe.unwatch()
break
except redis.exceptions.WatchError:
# 锁被修改,重试
pass
return False
# 使用锁来执行防止重复提交的逻辑
def process_submission(submission_id):
lock_name = f"lock:submission:{submission_id}"
# 尝试获取锁
identifier = acquire_lock(lock_name)
if identifier:
try:
# 执行提交逻辑
print(f"Processing submission ID {submission_id}")
time.sleep(5) # 模拟处理过程
print(f"Submission ID {submission_id} processed successfully")
阅读全文