Heim  >  Artikel  >  Datenbank  >  python使用redis实现协同控制的分布式锁

python使用redis实现协同控制的分布式锁

WBOY
WBOYOriginal
2016-06-07 16:41:291330Durchsuche

这两天心情不好,因为感情问题,在这里给朋友们都提个醒! 不要天天code,珍惜身边的人,别你妈天天宅家里,不是代码,就是撸管的。 上午的时候,有个腾讯的朋友问我,关于用zookeeper分布式锁的设计,他的需求其实很简单,就是节点之间的协同合作。 我以前

这两天心情不好,因为感情问题,在这里给朋友们都提个醒! 不要天天code,珍惜身边的人,别你妈天天宅家里,不是代码,就是撸管的。 

上午的时候,有个腾讯的朋友问我,关于用zookeeper分布式锁的设计,他的需求其实很简单,就是节点之间的协同合作。 我以前用redis写过一个网络锁,趁着这个机会就分享了出去。 

http://xiaorui.cc

其实核心的代码就那几行,就是借用redis的expire去set一个key。 

这是一个用redis实现的分布式锁,含有retry和timetout的功能。

麻痹的爬虫呀,哎,说明下原文地址是,http://xiaorui.cc

*   用with做锁的逻辑语句

*   timeout避免了避免了任务出现异常,没有做delete操作

*   对于长时间的业务,增加retry重试锁的次数

#coding:utf-8
#my blog: http://xiaorui.cc
from __future__ import with_statement
import redis
import time
from redis_netlock import dist_lock
client = redis.Redis(connection_pool=redis.BlockingConnectionPool(max_connections=15, host='localhost', port=6379))
with dist_lock('test', client):
    time.sleep(10)
    print 'welcome to my blog, http://xiaorui.cc'


同时运行test.py and test2.py

python test.py

root@li568-252 redis_netlock]# python test.py
welcome to my blog, http://xiaorui.cc

python test2.py

[root@li568-252 redis_netlock]# python test2.py
Sleeipng for 0.404031367603
Sleeipng for 1.19347232007
Sleeipng for 2.47668271021
Sleeipng for 4.55280708824
hello

已经把redis_netlock提交到了pypi项目里面。 

pip install redis_netlock


下面是redis_netlock的git地址。

git clone https://github.com/rfyiamcool/redis_netlock.git
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn