Python實現(xiàn)的redis分布式鎖功能示例
本文實例講述了Python實現(xiàn)的redis分布式鎖功能。分享給大家供大家參考,具體如下:
#!/usr/bin/env python
# coding=utf-8
import time
import redis
class RedisLock(object):
def __init__(self, key):
self.rdcon = redis.Redis(host='', port=6379, password="", db=1)
self._lock = 0
self.lock_key = "%s_dynamic_test" % key
@staticmethod
def get_lock(cls, timeout=10):
while cls._lock != 1:
timestamp = time.time() + timeout + 1
cls._lock = cls.rdcon.setnx(cls.lock_key, timestamp)
if cls._lock == 1 or (time.time() > cls.rdcon.get(cls.lock_key) and time.time() > cls.rdcon.getset(cls.lock_key, timestamp)):
print "get lock"
break
else:
time.sleep(0.3)
@staticmethod
def release(cls):
if time.time() < cls.rdcon.get(cls.lock_key):
print "release lock"
cls.rdcon.delete(cls.lock_key)
def deco(cls):
def _deco(func):
def __deco(*args, **kwargs):
print "before %s called [%s]."%(func.__name__, cls)
cls.get_lock(cls)
try:
return func(*args, **kwargs)
finally:
cls.release(cls)
return __deco
return _deco
@deco(RedisLock("112233"))
def myfunc():
print "myfunc() called."
time.sleep(20)
if __name__ == "__main__":
myfunc()
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
python內(nèi)置函數(shù)之eval函數(shù)詳解
這篇文章主要為大家介紹了python內(nèi)置函數(shù)之eval函數(shù),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01
Python中if __name__ == "__main__"詳細解釋
這篇文章主要介紹了Python中if __name__ == "__main__"詳細解釋,需要的朋友可以參考下2014-10-10
python smtplib模塊實現(xiàn)發(fā)送郵件帶附件sendmail
這篇文章主要為大家詳細介紹了python smtplib模塊實現(xiàn)發(fā)送郵件帶附件sendmail,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-05-05
python實現(xiàn)修改固定模式的字符串內(nèi)容操作示例
這篇文章主要介紹了python實現(xiàn)修改固定模式的字符串內(nèi)容操作,結(jié)合實例形式詳細分析了Python修改固定模式字符串原理、實現(xiàn)方法及相關(guān)操作注意事項,需要的朋友可以參考下2019-12-12

