Last active
December 22, 2023 03:46
-
-
Save dairoot/26fd78fa5ff63030db1cca1ec7ae19c2 to your computer and use it in GitHub Desktop.
分布式函数锁
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from redis import Redis | |
redis = Redis() | |
def setnx_lock(cache_time): | |
# 分布式锁 (原理 利用 setnx) | |
def decorator(func): | |
def wrapper(*args, ignore_lock=False, **kwargs): | |
redis_key = "func:{}:{}-{}".format(func.__name__, str(args), json.dumps(kwargs)) | |
print("缓存key:", redis_key) | |
is_lock = not redis.set(redis_key, "RUNNING", ex=cache_time, nx=True) # 原子性操作 | |
if not is_lock or ignore_lock: | |
func(*args, **kwargs) | |
# redis.set(redis_key, "SUSSCE", 5) | |
redis.delete(redis_key) | |
return True | |
else: | |
print("命中锁,无需执行") | |
return False | |
return wrapper | |
return decorator | |
if __name__ == '__main__': | |
@setnx_lock(cache_time=10) | |
def func1(t=""): | |
print(t, "\n") | |
func1("测试1") | |
func1("测试1", ignore_lock=True) # 忽略锁,强制执行 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment