Redis分布式锁的python实现
案例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实现的更多相关文章
- python redis分布式锁改进
0X01 python redis分布式锁通用方法 REDIS分布式锁实现的方式:SETNX + GETSET 使用Redis SETNX 命令实现分布式锁 python 版本实现上述思路(案例1) ...
- Redis分布式锁
Redis分布式锁 分布式锁是许多环境中非常有用的原语,其中不同的进程必须以相互排斥的方式与共享资源一起运行. 有许多图书馆和博客文章描述了如何使用Redis实现DLM(分布式锁管理器),但是每个库都 ...
- Lua脚本在redis分布式锁场景的运用
目录 锁和分布式锁 锁是什么? 为什么需要锁? Java中的锁 分布式锁 redis 如何实现加锁 锁超时 retry redis 如何释放锁 不该释放的锁 通过Lua脚本实现锁释放 用redis做分 ...
- Redlock(redis分布式锁)原理分析
Redlock:全名叫做 Redis Distributed Lock;即使用redis实现的分布式锁: 使用场景:多个服务间保证同一时刻同一时间段内同一用户只能有一个请求(防止关键业务出现并发攻击) ...
- 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. ...
- 利用redis分布式锁的功能来实现定时器的分布式
文章来源于我的 iteye blog http://ak478288.iteye.com/blog/1898190 以前为部门内部开发过一个定时器程序,这个定时器很简单,就是配置quartz,来实现定 ...
- redis分布式锁和消息队列
最近博主在看redis的时候发现了两种redis使用方式,与之前redis作为缓存不同,利用的是redis可设置key的有效时间和redis的BRPOP命令. 分布式锁 由于目前一些编程语言,如PHP ...
- redis咋么实现分布式锁,redis分布式锁的实现方式,redis做分布式锁 积极正义的少年
前言 分布式锁一般有三种实现方式:1. 数据库乐观锁:2. 基于Redis的分布式锁:3. 基于ZooKeeper的分布式锁.本篇博客将介绍第二种方式,基于Redis实现分布式锁.虽然网上已经有各种介 ...
- spring boot redis分布式锁
随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring b ...
随机推荐
- [容器]gcr.io镜像下载
下载gcr.io的镜像hosts文件 把下面两行加入到/etc/hosts中. 更多在这里http://wst.so/files/hosts 61.91.161.217 gcr.io 61.91.1 ...
- Spring的AOP配置
Spring的AOP配置 1.先写一个普通类: package com.spring.aop; public class Common { public void execute(String us ...
- 142. O(1) Check Power of 2【easy】
142. O(1) Check Power of 2[easy] Using O(1) time to check whether an integer n is a power of 2. Have ...
- Charles 的几个调试技巧
Charles 是一个网络调试的代理工具,类似 Windows 下的 Fildder,这里介绍下几个常用的调试技巧,使用的版本是 Charles 4. 1.移动端抓包 在移动开发中,经常会遇到在手机上 ...
- oracle 数据查询
1,读取从今天到1个月前之间的数据select * from tablewhere column between add_months(sysdate, -1) and sysdate;
- myeclipse中文编码错误,没有GBK选项
默认编码是UTF-8,但是导入GBK工程后,直接改为ISO-8859-1,但是还是编码错误. 用网上的: 全局编码设置:编码设置的方法:ToolBar-->Window-->Prefere ...
- Chai.js断言库API中文文档【转载】
基于chai.js官方API文档翻译.仅列出BDD风格的expect/should API.TDD风格的Assert API由于不打算使用,暂时不放,后续可能会更新. BDD expect和shoul ...
- Ubuntu安装特定版本安装包
Ubuntu安装特定版本安装包可以用aptitude,aptitude是apt-get的高级版,使用起来更强大. aptitude install package=version 比如我要安装2.6. ...
- spring mvc3.1 @ResponseBody注解生成大量Accept-Charset
Spring3 MVC使用@ResponseBody后会产生非常大的响应头(Accept-Charset会达到4K+).原因在于默认情况下StringHttpMessageConverter.writ ...
- tomcat添加crt证书
使用keytool生成证书苹果手机添加后提示未验证,可以使用Apache的openssl生成证书导入到tomcat中. 使用Apache 生成证书:openssl genrsa 4096 > s ...