成都創(chuàng)新互聯(lián)專注于平陰企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站,商城開發(fā)。平陰網(wǎng)站建設(shè)公司,為平陰等地區(qū)提供建站服務(wù)。全流程按需網(wǎng)站策劃,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
利用Python+redis實(shí)現(xiàn)分布式鎖
歡迎一起交流技術(shù):一個(gè)人可以走的很快,但是一群人卻可以走的更遠(yuǎn)。
常見關(guān)系型數(shù)據(jù)庫(Oracle+MySQL+PG+GP)+高可用企業(yè)解決方案+分布式鎖
使用場景:
徹底解決HA的腦裂問題
多個(gè)服務(wù)器之間只允許一個(gè)進(jìn)程執(zhí)行的場景
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