案例1:

#!/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(""))
def myfunc():
print "myfunc() called."
time.sleep(20) if __name__ == "__main__":
myfunc()

案例2:

import redis
import time, datetime def acquire_lock(conn, lockname, identifier, expire=10):
if conn.setnx(lockname, identifier):
conn.expire(lockname, expire)
return identifier
elif not conn.ttl(lockname):
conn.expire(lockname, expire) return False def release_lock(conn, lockname, identifier):
pipe = conn.pipeline(True)
while True:
try:
pipe.watch(lockname)
if pipe.get(lockname) == identifier:
pipe.multi()
pipe.delete(lockname)
pipe.execute()
return True
pipe.unwatch()
break
except redis.exceptions.WatchError:
pass # we lost the lock
return False conn = redis.Redis(host='localhost', port=6379, db=0) # 1 identifier
# 2 False
# 11 True
# 22 False
# 33 barx2
# 44 True ret = acquire_lock(conn, "lockname", "identifier", 3)
print "", ret
ret = acquire_lock(conn, "lockname", "identifier", 3)
print "", ret
ret = release_lock(conn, "lockname", "identifier")
print "", ret
ret = release_lock(conn, "lockname", "identifier")
print "", ret ret = acquire_lock(conn, "footest", "bartest", 10)
print "", ret

参考文档:

https://blog.csdn.net/weixin_39471249/article/details/79121291

http://xiaorui.cc/2014/12/19/python%E4%BD%BF%E7%94%A8redis%E5%AE%9E%E7%8E%B0%E5%8D%8F%E5%90%8C%E6%8E%A7%E5%88%B6%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/

https://www.cnblogs.com/SimplifyIT/p/6691584.html

Redis分布式锁的python实现的更多相关文章

  1. python redis分布式锁改进

    0X01 python redis分布式锁通用方法 REDIS分布式锁实现的方式:SETNX + GETSET 使用Redis SETNX 命令实现分布式锁 python 版本实现上述思路(案例1) ...

  2. Redis分布式锁

    Redis分布式锁 分布式锁是许多环境中非常有用的原语,其中不同的进程必须以相互排斥的方式与共享资源一起运行. 有许多图书馆和博客文章描述了如何使用Redis实现DLM(分布式锁管理器),但是每个库都 ...

  3. Lua脚本在redis分布式锁场景的运用

    目录 锁和分布式锁 锁是什么? 为什么需要锁? Java中的锁 分布式锁 redis 如何实现加锁 锁超时 retry redis 如何释放锁 不该释放的锁 通过Lua脚本实现锁释放 用redis做分 ...

  4. Redlock(redis分布式锁)原理分析

    Redlock:全名叫做 Redis Distributed Lock;即使用redis实现的分布式锁: 使用场景:多个服务间保证同一时刻同一时间段内同一用户只能有一个请求(防止关键业务出现并发攻击) ...

  5. Why failover-based implementations are not enough Redis分布式锁实现 SET resource_name my_random_value NX PX 30000

    核心 SET resource_name my_random_value NX PX 30000 Distributed locks with Redis – Redis https://redis. ...

  6. 利用redis分布式锁的功能来实现定时器的分布式

    文章来源于我的 iteye blog http://ak478288.iteye.com/blog/1898190 以前为部门内部开发过一个定时器程序,这个定时器很简单,就是配置quartz,来实现定 ...

  7. redis分布式锁和消息队列

    最近博主在看redis的时候发现了两种redis使用方式,与之前redis作为缓存不同,利用的是redis可设置key的有效时间和redis的BRPOP命令. 分布式锁 由于目前一些编程语言,如PHP ...

  8. redis咋么实现分布式锁,redis分布式锁的实现方式,redis做分布式锁 积极正义的少年

    前言 分布式锁一般有三种实现方式:1. 数据库乐观锁:2. 基于Redis的分布式锁:3. 基于ZooKeeper的分布式锁.本篇博客将介绍第二种方式,基于Redis实现分布式锁.虽然网上已经有各种介 ...

  9. spring boot redis分布式锁

    随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring b ...

随机推荐

  1. 【转载】checkbox复选框的一些深入研究与理解

    转载来自:原创文章,转载请注明来自张鑫旭-鑫空间-鑫生活[http://www.zhangxinxu.com] 一.一开始的唠叨最近忙于开发,自淫于项目的一步步完工,心浮躁了.舍近而求远,兵家之大忌. ...

  2. 【Nginx-反向代理server】基础知识(二)之多进程模式

    Nginx的多进程模式 nginx在启动后.会有一个master进程和多个worker进程.master进程主要用来管理worker进程,包括:接收来自外界的信号.向各worker进程发送信号,监控w ...

  3. nyoj304 节能

    节能 时间限制:1000 ms  |  内存限制:65535 KB 难度:5 描述 Dr.Kong设计的机器人卡多越来越聪明.最近市政公司交给卡多一项任务,每天早晨5:00开始,它负责关掉ZK大道右侧 ...

  4. Goole Python 风格指南 中文版

    http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/

  5. codeblocks设置当前行高亮

    默认是不开启当前行高亮的. 如果想打开,选择:Settings>Editor>Editor Settings>Other options> 勾选Highlight line u ...

  6. C++ Primer(第五版)读书笔记 & 习题解答 --- Chapter 2

    Chapter 2.1 1. 数据类型决定了程序中数据和操作的意义. 2. C++定义了一套基本数据类型,其中包括算术类型和一个名为void的特殊类型.算术类型包含了字符.整型.布尔值以及浮点数.vo ...

  7. C# 子类实例化过程

    刚研究了一下C#子类实例化的过程. 首先我遇到了如下一个问题: 有类A,里面写了一个有参的构造函数,并没有提供默认的无参构造函数.现在类B继承了类A,没有写任何的构造函数. 这时如果想实例化类B就会产 ...

  8. 用kaptcha生成验证码

    1.新建web项目,导入jar包:kaptcha-2.3.jar 2.配置web.xml代码如下: <?xml version="1.0" encoding="UT ...

  9. IOS设计模式浅析之建造者模式(Builder)

    定义 "将一个复杂对象的构建与它的表现分离,使得同样的构建过程可以创建不同的表现". 最初的定义出现于<设计模式>(Addison-Wesley,1994). 看这个概 ...

  10. VLC Web插件的浏览器兼容性

    网页插件实现原理 IE浏览器基于Activex插件来实现,非IE浏览器采用NPAPI来实现,所以,非浏览器需要支持NPAPI来实现. IE浏览器 FF浏览器(版本小于52) 原因从 Firefox 版 ...