PythonTip >> 博文 >> chinaunix

Zookeeper和zkpython

zihua 2014-01-13 18:01:01 点击: 816 | 收藏


1. zookeeper 下载地址 
http://zookeeper.apache.org/releases.html

2.zookeeper 安装 python中有一个zkpython的包,是基于zookeeper的c-client开发的,所以安装的时候需要先安装zookeeper的c客户端。安装步骤如下
http://mirrors.cnnic.cn/apache/zookeeper/current/zookeeper-3.4.5.tar.gz
tar xzvf zookeeper-3.4.5.tar.gz
cd zookeeper-3.4.5/src/c/
./configure
make
make install

3.zkpython 安装
wget https://pypi.python.org/packages/source/z/zkpython/zkpython-0.4.2.tar.gz
tar xzvf zkpython-0.4.2.tar.gz
cd zkpython-0.4.2
python setup.py install
【老点的版本一直提示找不到zookeeper.h头文件  可以调整setup.py 中include_dirs 路径的指向】
import zookeeper时 报 库文件缺失 可以
 export LD_LIBRARY_PATH=/usr/lib:/usr/local/lib:/lib:(指定缺失库文件位置) 】

测试结果 安装成功
[root@datacenter1 ~]# python
Python 2.6.6 (r266:84292, Feb 22 2013, 00:00:18)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import zookeeper
>>> print zookeeper.__version__
3.4.5
>>>


4. demo 可从开源站点获取
https://github.com/piglei/zkpython_example


5.demo 运行结果
 这个简单的demo所做的事情,就是通过在zookeeper的/app/workers节点下建立临时的子节点( flags=zookeeper.EPHEMERAL | zookeeper.SEQUENCE ),每次create完成之后检查自己是不是在最小的MASTERS_NUM(例子中为1,即单master)里。如果是的话,作为master运行,否 则的话,作为slave运行。

  这样的话,当我们的master挂掉以后,与zookeeper之间的连接也会中断,过了指定的TIMEOUT以后,master之前在 worker下的子节点就会被删除,于是slave节点之前设置的watcher会被触发,再次检查自己是否为master,如果是的话则完成切换。

demo运行结果:



# 第一个实例
Connected in 20 ms, handle is 0
[2011-09-09 12:40:43,702] INFO     login ok!
Node /app/workers/worker created in 4 ms
[2011-09-09 12:40:43,708] INFO     [ worker0000000022(slave) ] register ok! I'm worker0000000022
[2011-09-09 12:40:43,709] INFO     [ worker0000000022(slave) ] /app/workers's children: ['worker0000000022']
[2011-09-09 12:40:43,709] INFO     [ worker0000000022(master) ] I've become master!
 
# 这时再起第二个实例
Connected in 64 ms, handle is 0
[2011-09-09 12:43:08,334] INFO     login ok!
Node /app/workers/worker created in 11 ms
[2011-09-09 12:43:08,346] INFO     [ worker0000000023(slave) ] register ok! I'm worker0000000023
[2011-09-09 12:43:08,347] INFO     [ worker0000000023(slave) ] /app/workers's children: ['worker0000000022', 'worker0000000023']
[2011-09-09 12:43:08,347] INFO     [ worker0000000023(slave) ] ['worker0000000022'] is masters, I'm slave
 
# 杀掉master,第二个实例发生的变化
[2011-09-09 12:44:06,016] INFO     [ worker0000000023(slave) ] child changed, try to get master again.
[2011-09-09 12:44:06,017] INFO     [ worker0000000023(slave) ] /app/workers's children: ['worker0000000023']
[2011-09-09 12:44:06,017] INFO     [ worker0000000023(master) ] I've become master!

原文链接:http://blog.chinaunix.net/uid-21505614-id-4063798.html

作者:zihua | 分类: chinaunix | 标签: python | 阅读: 816 | 发布于: 2014-01-13 18时 |