python实现redis分布式锁
短信预约 -IT技能 免费直播动态提醒
#!/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()
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341