当前位置:网站首页>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()边栏推荐
- Shell script text three swordsman awk
- NPM step pit
- Leetcode 01: t1. sum of two numbers; T1108. IP address invalidation; T344. Reverse string
- Weibo comment crawler + visualization
- 解决@OneToMany查询陷入循环引用问题
- STM32编译出现error: L6235E: More than one section matches selector - cannot all be FIRST/L
- Could not load dynamic library ‘libcudnn.so.8‘;
- Detailed explanation of hash table
- Shell脚本文本三剑客之sed
- LeetCode 03: T58. 最后一个单词的长度(简单); 剑指 Offer 05. 替换空格(简单); 剑指 Offer 58 - II. 左旋转字符串(简单)
猜你喜欢

Newton Raphson iterative method

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

The first case of monkeypox in pregnant women in the United States: the newborn was injected with immunoglobulin and was safely born

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

Keil MDK编译出现..\USER\stm32f10x.h(428): error: #67: expected a “}“错误的解决办法

Shell脚本文本三剑客之awk

MySQL数据库主从复制集群原理概念以及搭建流程

NPM step pit

Regular expression of shell programming (grep of shell script text three swordsmen)

Japan Fukushima waste dump safety monitoring agreement will recognize the "safety" of the sea discharge plan
随机推荐
go入门篇 (2)
STS下载教程(include官网无法下载解决方案)
JS string method summary
Sword finger offer notes: T53 - ii Missing numbers from 0 to n-1
SMA TE: Semi-Supervised Spatio-Temporal RepresentationLearning on Multivariate Time Series
广东财政多举措助力稳住粮食安全“压舱石”
TapNet: Multivariate Time Series Classification with Attentional Prototypical Network
Finding the finite zero point of transfer function under different sampling periods
Sword finger offer note: t45. arrange the array into the smallest number
Matlab draws Bode diagram with time delay system
go 用本地代码replace
go入门篇 (4)
IDEA: Can‘t use Subversion command line client:svn 解决方案
Idea: can't use subversion command line client: SVN solution
How to make a graph? Multiple subgraphs in a graph are histogram (or other graphs)
Database cli tool docker image
compute_class_weight() takes 1 positional argument but 3 were given
N ¨UWA: Visual Synthesis Pre-training for Neural visUal World creAtionChenfei
Beyond compare 3 next difference segment / down search arrow not found
二分查找判定树(二分查找树平均查找长度)