Parcourir la source

redis增加分布式锁

zhangdongming il y a 1 an
Parent
commit
3b6d2fa98e
2 fichiers modifiés avec 43 ajouts et 2 suppressions
  1. 39 0
      Object/RedisObject.py
  2. 4 2
      Object/ResponseObject.py

+ 39 - 0
Object/RedisObject.py

@@ -113,3 +113,42 @@ class RedisObject:
 
     def set_persist(self, key):
         return self.CONN.persist(key)
+
+    def try_lock(self, lock_key, request_id, expire, time_unit_second):
+        """
+        获取分布式锁 原子性
+        :param lock_key: 锁的key
+        :param request_id: 请求id
+        :param expire: 锁过期时间
+        :param time_unit_second: 时间单位(秒)
+        :return: True or False
+        """
+        try:
+            # 使用set命令尝试获取锁,并设置nx=True
+            result = self.CONN.set(lock_key, request_id, ex=time_unit_second * expire, nx=True)
+            return result is not None
+        except Exception as e:
+            print("redis lock error.", e)
+            return False
+
+    def release_lock(self, lock_key, request_id):
+        """
+        释放锁
+        :param lock_key: 锁的key
+        :param request_id: 请求id
+        :return: True or False
+        """
+        try:
+            # 使用Lua脚本来释放锁,避免在执行脚本时发生异常导致锁无法释放
+            lua_script = """
+            if redis.call('get', KEYS[1]) == ARGV[1] then
+                return redis.call('del', KEYS[1])
+            else
+                return 0
+            end
+            """
+            result = self.CONN.eval(lua_script, 1, lock_key, request_id)
+            return result == 1
+        except Exception as e:
+            print("redis unlock error.", e)
+            return False

+ 4 - 2
Object/ResponseObject.py

@@ -149,7 +149,8 @@ class ResponseObject(object):
             503: 'The operation failed, please try again later',
             10071: 'The successful collection can be viewed in Settings - 4G-My package',
             10072: 'This function has been disabled. Please contact the administrator',
-            10073: 'The verification code has been sent, please pay attention to check'
+            10073: 'The verification code has been sent, please pay attention to check',
+            10074: 'Task queue processing, please try again later'
         }
         data_cn = {
             0: '成功',
@@ -285,7 +286,8 @@ class ResponseObject(object):
             503: '操作失败,请稍后重试',
             10071: '\t领取成功\n可在设置-4G-我的套餐中查看',
             10072: '该功能已停用,请联系管理员',
-            10073: '验证码已发送,请注意查收'
+            10073: '验证码已发送,请注意查收',
+            10074: '任务队列处理中,请稍后再试'
         }
 
         msg = data_cn if self.lang == 'cn' or self.lang == 'zh-Hans' or self.lang == 'zh-Hant' else data_en