python使用zookeeper

本文详细介绍了ZooKeeper的安装步骤,包括下载、配置及启动,并演示了如何在Python环境中使用tooz和kazoo库进行锁操作的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值