| 15 | memory_cache = caches['default'] |
| 16 | |
| 17 | class RedisLock(): |
| 18 | def __init__(self): |
| 19 | self.lock_value = None |
| 20 | |
| 21 | def try_lock(self, key: str, timeout=None): |
| 22 | """ |
| 23 | 获取锁 |
| 24 | :param key: 获取锁 key |
| 25 | :param timeout 超时时间 |
| 26 | :return: 是否获取到锁 |
| 27 | """ |
| 28 | redis_client = get_redis_connection("default") |
| 29 | if timeout is None: |
| 30 | timeout = 3600 # 默认超时时间为3600秒 |
| 31 | self.lock_value = str(uuid.uuid7()) |
| 32 | return redis_client.set(key, self.lock_value, nx=True, ex=timeout) |
| 33 | |
| 34 | |
| 35 | def un_lock(self, key: str): |
| 36 | """ |
| 37 | 解锁 |
| 38 | :param key: 解锁 key |
| 39 | :return: 是否解锁成功 |
| 40 | """ |
| 41 | redis_client = get_redis_connection("default") |
| 42 | unlock_script = """ |
| 43 | if redis.call("get", KEYS[1]) == ARGV[1] then |
| 44 | return redis.call("del", KEYS[1]) |
| 45 | else |
| 46 | return 0 |
| 47 | end |
| 48 | """ |
| 49 | redis_client.eval(unlock_script, 1, key, self.lock_value) |
| 50 | |
| 51 | |
| 52 | def lock(lock_key, timeout=None): |
no outgoing calls
no test coverage detected