zoukankan      html  css  js  c++  java
  • 利用Python+Redis实现分布式锁

    class MyDLock(object):
        def __init__(self, lockID,timeout):
            self.connection = redis.Redis(host=cfg.REDIS_SERVER_IP, port=cfg.REDIS_SERVER_PORT, password=cfg.REDIS_SERVER_PWD, db=cfg.REDIS_SERVER_DB_NUM,decode_responses=True)
            self.__lockID = lockID
            self.__timeout  = timeout
    
        def tryLock(self, appid):
            #To_Main
            try:
                val=self.connection.get(self.__lockID)
                if val is None:
                    logging.info("The app(%s) try lock(%s) ok." % (appid, self.__lockID));
                    self.connection.set(self.__lockID, appid, ex=self.__timeout)
                    return True
                else:
                    logging.info("The owner of lock(%s) is %s. you(%s) can not get it"%(self.__lockID, val, appid));
                    return False
            except Exception as e:
                logging.error("Warning: Can't write log. (%s)" % e)
                return False
    
        def activeLock(self, appid):
            #心跳,定期激活
            val = self.connection.get(self.__lockID)
            if val is None:
                logging.info("There is no lock(%s)." % (self.__lockID));
                return False
            else:
                if appid == val:
                    #只能激活自己的锁
                    logging.info("Application(%s) active lock(%s) ok." % (appid, self.__lockID));
                    self.connection.set(self.__lockID, appid, ex=self.__timeout)
                    return True
                else:
                    #不能激活非自己的锁
                    logging.info("Application(%s) can not active lock(%s). The owner is (%s)" % (appid, self.__lockID, val));
                    return False
    
        def releaseLock(self, key, appid):
            val = self.connection.get(self.__lockID)
            if val is None:
                return False
            else:
                if appid == val:
                    # 只能删除自己的锁
                    self.connection.delete(self.__lockID)
                    return True
                else:
                    # 不能删除非自己的锁
                    return False
  • 相关阅读:
    pycharm 操作excel
    pycharm 增删改查 mysql数据库
    fillder 抓包工具详解
    acunetix 12.0.190902105 破解方法
    Navicat15 最新版本破解版操作步骤
    网站性能优化检测工具
    linux 服务器资源 监控工具
    win10系统git的安装与使用命令
    测试入门基础知识
    Pycharm2020.2 专业版永久激活 免费下载激活插件与参数
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10799007.html
Copyright © 2011-2022 走看看