您好,登錄后才能下訂單哦!
利用Python+Redis實現分布式鎖
歡迎一起交流技術:一個人可以走的很快,但是一群人卻可以走的更遠。
常見關系型數據庫(Oracle+MySQL+PG+GP)+高可用企業解決方案+分布式鎖
使用場景:
徹底解決HA的腦裂問題
多個服務器之間只允許一個進程執行的場景
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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。