dongzhaorui 2 years ago
parent
commit
8391d75188
1 changed files with 23 additions and 23 deletions
  1. 23 23
      find_source/crawler/bloom_filter/utils.py

+ 23 - 23
find_source/crawler/bloom_filter/utils.py

@@ -4,14 +4,14 @@
 # @File    : utils.py
 # @Software: PyCharm
 # @Python3.6
-import io
-import uuid
 import math
 import time
+import uuid
+
 import redis
 
 
-# 获取锁
+# 获取锁(乐观锁)
 def acquire_lock_with_timeout(conn, lockname, acquire_timeout=5, lock_timeout=10):
     # 128位随机标识符
     identifier = str(uuid.uuid4())
@@ -30,28 +30,28 @@ def acquire_lock_with_timeout(conn, lockname, acquire_timeout=5, lock_timeout=10
     return False
 
 
-# 释放锁
+# 释放锁(乐观锁)
 def release_lock(conn, lockname, identifier):
-    pipe = conn.pipeline(True)
     lockname = 'lock:' + lockname
-    while True:
-        # try:
-        pipe.watch(lockname)
-        value = pipe.get(lockname)
-        # 判断标志是否相同
-        if value is not None and value.decode() == identifier:
-            pipe.multi()
-            pipe.delete(lockname)
-            pipe.execute()
-            return True
-
-        # 不同则直接退出 return False
-        pipe.unwatch()
-        break
-
-        # except (redis.exceptions.WatchError, TypeError):
-        #     pass
-    return False
+    with conn.pipeline(True) as pipe:
+        while True:
+            try:
+                pipe.watch(lockname)
+                value = pipe.get(lockname)
+                # 判断标志是否相同
+                if value is not None and value.decode() == identifier:
+                    pipe.multi()
+                    pipe.delete(lockname)
+                    pipe.execute()
+                    return True
+
+                # 不同则直接退出 return False
+                pipe.unwatch()
+                break
+            except redis.exceptions.WatchError:
+                pass
+
+        return False
 
 
 # if __name__ == '__main__':