zk节点复制
zk node复制,网上较多的方案是使用zkcopy来解决问题,但是zkcopy的前提是两台服务器的网络互通,若网络不通则无法进行copy.
zkcopy github地址: https://github.com/ksprojects/zkcopy, 有需要可以自取.
当前方案是用Python将节点写出来,然后再将节点写入
读取节点并持久化
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: yxhe
# Date: 2020/11/23/0023 9:53
# ----------------------------------------------------------
from kazoo.client import KazooClient,KazooState
from bson import json_util
# 测试zk_walk的打印回调函数,只是把所有数据都打印出来
def printZNode(node, data, stat, children):
print("node : " + node)
print("data : " + str(data))
print("stat : " + str(stat))
print("child : " + str(children))
print '\n'
# 递归遍历所有节点的子节点函数,_zk是KazooClient的对象,node是节点名称字符串,func是回调函数
def zk_walk(map, _zk, node, func):
data, stat = _zk.get(node)
children = _zk.get_children(node)
func(node, data, stat, children)
map[node] = data
if len(children) > 0:
for sub in children:
# 这里可以过滤一些不需要的节点,如/zookeeper或/test/test
if node == '/zookeeper' or node == '/test/test':
break
sub_node = ''
if node != '/':
sub_node = node + '/' + sub
else:
sub_node = '/' + sub
zk_walk(map, _zk, sub_node, func)
def write_file(result, filename):
fp = open(filename, 'a')
fp.write(json_util.dumps(result))
fp.close()
if __name__ == '__main__':
# hosts为待复制的zk机器
_zk = KazooClient(hosts='127.0.0.1:2181', timeout=10.0)
_zk.start()
map = {}
zk_walk(map, _zk, '/', printZNode)
write_file(map, "zkNode.csv")
导出的文件会保存在zkNode.csv的文件中
读取文件并复制到目标zk
def zk_node_init():
with open("resource/MarkingPlatform/data/zkNode.csv", "r") as f: # 打开文件
data = f.read() # 读取文件
map = json_util.loads(data)
# 这里需要一个排序,因为在data序列化的时候顺序会乱,此时会存在先创建了/a/b 但是/a节点还未创建,就会报错
sort_index = [
"/a",
"/a/a",
"/b/b",
"/c/c"
]
zkc = KazooClient(hosts=conf.get('db', 'zookeeper_uri'), timeout=10.0)
zkc.start()
for key in sort_index:
if zkc.exists(key):
print key, "存在"
else:
if len(map[key]) == 0:
# 建立节点,成功后返回新节点路径
childrenPath = zkc.create(key)
else:
data = map[key]
childrenPath = zkc.create(key, str(data))
print "创建节点:", childrenPath, "成功"
时在中春,阳和方起