当前位置:网站首页>Kazoo tutorial
Kazoo tutorial
2022-07-27 11:57:00 【Big leaves are not small】
kazoo It's a Python library , It aims to make Python Be able to relax 、 Easy to use zookeeper.
kazoo Installation
Use pip install kazoo:
pip install kazoobecause kazoo Use pure python Realization zookeeper The agreement , So you don't have to install Python zookeeper C All kinds of dependence .
Basic usage
Connection processing
Use kazoo, First you need to instantiate a KazooClient Object and establish a connection , The code is as follows :
from kazoo.client import KazooClient
zk = KazooClient(hosts="127.0.0.1:2181")
zk.start()By default ,KazooClient Will connect to the local network zookeeper service , The port number is 2181.
When zookeeper When the service is abnormal ( Service exception or service not started ),zk.start() Will keep trying to reconnect , Until the connection times out .
Once the connection is established , Whether it's intermittent connection loss ( Network flash off and so on ) or zookeeper Session expiration, ,KazooClient Will keep trying to reconnect .
We can go through stop Command to explicitly disconnect :
zk.stop()Conversation state
Kazoo Your client is working with zookeeper During the service session , It usually switches between the following three states :CONNECTED、 SUSPENDED、LOST.
When KazooClient When the instance is first created , Its state is LOST, Once the connection is established , The state is then switched to CONNECTED.
Throughout the life cycle of the session , With the network flash off 、 Server side zookeeper Abnormal or other reasons , The client and server are disconnected ,KazooClient Switch to SUSPENDED, meanwhile ,KazooClient Will keep trying to reconnect to the server , Once the connection is successful , The state goes back to CONNECTED.
kazoo State monitoring
Add status listening Events , Monitor the session status of client and server in real time , Once the connection is interrupted 、 When the connection is restored or the session expires , We can deal with it in time . Its usage is as follows :
def connection_listener(state):
if state == "LOST":
# Register somewhere that the session was lost
pass
elif state == "SUSPENDED":
# Handle being disconnected from Zookeeper
pass
else:
# Handle being connected/reconnected to Zookeeper
pass
zk = KazooClient(hosts="127.0.0.1:2181")
zk.add_listener(connection_listener)When using kazoo.recipe.lock.Lock Or when creating temporary nodes , It is highly recommended that you add status monitoring , So that our code can correctly handle connection interruption or Zookeeper Case of session loss .
zookeeper Addition, deletion and modification of
Create nodes
Method :
- ensure_path(): Create node paths recursively , Only permissions can be set , Can't add data .
- create(): Create nodes , And you can add data and listen for events at the same time , The premise is that its parent node must exist , Cannot create recursively .
usage :
zk.ensure_path("/china/henan")
zk.create("/china", b"this is china node.")Reading data
Method :
- exists(): Check whether the node exists
- get(): Get node data and node status details
- get_children(): Gets all child nodes of the specified node
Update data
Method :
- set(): Update the information of the specified node .
Delete node
Method :
- delete(): Delete the specified node .
Monitor
kazoo You can add listening on the node , So that it can be triggered when the node or the child nodes of the node change .
kazoo Support two types of ways to add listeners , One is zookeeper Native supported , Its usage is as follows :
def test_watch_data(event):
print("this is a watcher for node data.")
zk.get_children("/china", watch=test_watch_children)Another way is through python The principle and implementation of modifier , There are ways to support this function :
- ChildrenWatch: Triggered when the child node changes
- DataWatch: Trigger when the node data changes
Its usage is as follows :
@zk.ChildrenWatch("/china")
def watch_china_children(children):
print("this is watch_china_children %s" % children)
@zk.DataWatch("/china")
def watch_china_node(data, state):
print("china node is %s" % data)kazoo Business
since v3.4 in the future ,zookeeper Support sending multiple commands at a time , These commands are submitted as an atom , Or it all works , All or nothing .
How to use it is as follows :
transaction = zk.transaction()
transaction.check('/china/hebei', version=3)
transaction.create('/china/shanxi', b"thi is shanxi.")
results = transaction.commit()边栏推荐
- EfficientNet
- Sword finger offer notes: t57 - I. and two numbers of S
- 解决方案:Can not issue executeUpdate() or executeLargeUpdate() for SELECTs
- Analysis of the use of JUC framework from runnable to callable to futuretask
- Conversion between multiple bases
- 微信小程序必用接口「建议收藏」
- Adobe audit prompts that the sampling rate of audio input does not match the output device - problem solving
- Shell脚本文本三剑客之sed
- 严控室外作业时间!佛山住建局发文:加强高温期间建筑施工安全管理
- 快抖抢救“失意人”
猜你喜欢

B 站 713 事故后的多活容灾建设|TakinTalks 大咖分享

【产品】关于微信产品分析

JS parasitic combinatorial inheritance

N ¨UWA: Visual Synthesis Pre-training for Neural visUal World creAtionChenfei

Shell script text three swordsmen sed

箱型图介绍

Newton Raphson iterative method

【无标题】多模态模型 CLIP

求不同采样周期下的传递函数有限零点

Tlc549proteus simulation &sallen key filter &ad736vrms to DC conversion &proteus view 51 register value
随机推荐
N ¨UWA: Visual Synthesis Pre-training for Neural visUal World creAtionChenfei
CH340模块无法识别/烧写不进的一种可能性
日本福岛废堆安全监视协议会认可排海计划“安全”
EfficientNet
JS字符串方法总结
In the first half of the year, the number of fires decreased by 27.7%. Guangdong will improve the fire safety quality of the whole people in this way
[machine learning whiteboard derivation series] learning notes --- conditional random fields
Synchronous use reference of the new version of data warehouse (for beginners)
STM32编译出现error: L6235E: More than one section matches selector - cannot all be FIRST/L
SMA TE: Semi-Supervised Spatio-Temporal RepresentationLearning on Multivariate Time Series
Arduino常见供电问题与解决
IDEA: Can‘t use Subversion command line client:svn 解决方案
go入门篇 (3)
剑指 Offer 笔记: T45. 把数组排成最小的数
Can you really write binary search - variant binary search
系统临时文件的写和读:createTempFile和tempFileContent[通俗易懂]
Vscode removes style / syntax highlighting / code highlighting / black background when copying code
LeetCode 03: T58. 最后一个单词的长度(简单); 剑指 Offer 05. 替换空格(简单); 剑指 Offer 58 - II. 左旋转字符串(简单)
检定和校准的区别
mysql分页查询实例_mysql分页查询实例讲解「建议收藏」