1.安装zookeeper
1)下载
wget http://apache.01link.hk/zookeeper/zookeeper-3.4.14/zookeeper-3.4.14.tar.gz
2)安装
tar -zxvf zookeeper-3.4.14.tar.gz
cd zookeeper-3.4.11/conf
cp zoo_sample.cfg zoo.cfg
vi zoo.cfg 写入:
---------------------------------------------------
#默认心跳时间,默认为2秒
tickTime=2000
#LF初始通信时限
initLimit=10
#zookeeper保存的内存快照,以及事务日志的目录
dataDir=/tmp/zookeeper
#默认端口
clientPort=2181
----------------------------------------------------
3)启动/停止
sh bin/zkServer.sh start
sh bin/zkServer.sh stop
2.在python中使用
1)安装tooz和kazoo
pip install tooz kazoo
2)测试锁的使用
import time
from tooz import coordination
coordinator = coordination.get_coordinator('kazoo://localhost:2181', b'host-1')
coordinator.start()
lock = coordinator.get_lock("test")
try:
with lock:
while True:
print "Locked in test"
time.sleep(1)
except KeyboardInterrupt:
coordinator.stop()
import time
from atexit import register
from tooz import coordination
coordinator = coordination.get_coordinator('kazoo://localhost:2181', b'host-2')
coordinator.start()
lock = coordinator.get_lock("test1")
try:
with lock:
while True:
print "Locked in test1"
time.sleep(1)
except KeyboardInterrupt:
register(coordinator.stop)
from tooz import coordination
import time
coordinator1 = coordination.get_coordinator('kazoo://localhost:2181', b'host-3')
coordinator2 = coordination.get_coordinator('kazoo://localhost:2181', b'host-4')
coordinator3 = coordination.get_coordinator('kazoo://localhost:2181', b'host-5')
coordinator1.start()
coordinator2.start()
coordinator3.start()
lock1 = coordinator1.get_lock("test")
lock2 = coordinator2.get_lock("test1")
lock3 = coordinator3.get_lock("test")
if lock1.acquire(100):
print "get lock"
time.sleep(5)
print "release test"
coordinator1.stop()
if lock2.acquire(100):
print "get lock"
time.sleep(5)
print "released test1"
coordinator2.stop()
if lock3.acquire(100):
print "get lock"
time.sleep(5)
print "released test"
coordinator3.stop()
可以在后台看到创建的锁
sh bin/zkCli.sh -server localhost:2181 #连接到zookeeper服务器
[外链图片转存失败(img-BDohy8AG-1562562835776)(https://s2.ax1x.com/2019/07/08/ZrCw5t.png)]