Using Python+Redis to realize distributed Lock
Using Python+Redis to realize distributed Lock
Welcome to share technology: one person can go fast, but a group of people can go further.
Common relational databases (Oracle+MySQL+PG+GP) + highly available enterprise solutions + distributed locks
Use the scene:
Completely solve the problem of brain fissure in HA
A scenario in which only one process is allowed to execute between multiple servers
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):
# heartbeat, activate periodically
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:
# only activate your own locks
Logging.info ("Application (% s) active lock (% s) ok." (appid, self.__lockID))
Self.connection.set (self.__lockID, appid, ex=self.__timeout)
Return True
Else:
# cannot activate locks that are not your own
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:
# you can only delete your own locks
Self.connection.delete (self.__lockID)
Return True
Else:
# you cannot delete locks that are not your own
Return False