这是 kazoo readthedocs 上提到的代码
election=zk.Election("/electionpath", "my-identifier")
要传递哪些输入参数才能使特定节点成为领导者? (即 /electionpath 和 my-identifier 在这里指什么?)
简而言之:“/electionpath”是您感兴趣的路径,您将在其中创建节点、添加数据并使用 dataWatchers 监视节点。 “my-identifier”是不可重入锁的标识符,它将用于验证谁是竞争者中的领导者,并只允许写入领导者。
详细: 为了简化它,首先解释为什么动物园管理员应该有领导者。领导者负责执行所有写入操作和连接相关处理。 考虑以下示例来理解领导者选举的概念。
在[1]中:zk_client.create('test_zk/path_of_interest/test_ephemeral', 短暂=真实)
在[9]中:zk_client.get("test_zk/path_of_interest/test_ephemeral")
输出[9]: ('',ZnodeStat(czxid=678608988239, mzxid=687195015354, ctime=1476960597584,mtime=1477310417594,版本=1145,cversion=0, 厌恶=0,临时所有者=0,数据长度=185,numChildren=0, pzxid=678608988239))
创建id(czxid)最小的节点将在leader选举过程中被选举为leader。
领导者选举在内部为当选节点(最小的 czxid)提供不可重入锁,并为该锁设置一些标识符,该标识符将用于验证谁是竞争者中的领导者(您的“我的标识符”)。
现在让我们看看选举领导者的实际代码。
In [7]: election = zk_client.Election('/test_zk/path_of_interest', 'test-election')
In [8]: def leader_func():
...: print 'Election Completed...!'
...:
In [9]: election.run(leader_func)
Election Completed...!
可调用对象被传递给 run 方法来执行一些选举后的操作。
我希望这有帮助。
下面的代码说明了Leader选举和follower策略的正确使用。所有追随者继续参与选举,直到领导者去世或自愿放弃领导权。 您可以从终端或终止符运行代码的多个实例。在启动代码之前确保 Zookeeper 的本地实例正在运行:
import time
from kazoo.client import KazooClient
def leader_callback():
"""Blocking call, until an input "y" is provided"""
#Do the leader stuff"""
ans = None
while ans != "y":
time.sleep(1) # to let others join the leadership race
print(election.contenders())
ans = input('''I am the king now, Shall I abdicate the throne? (y/n)\n''')
return
def do_follower_stuff():
# poll to check if leader or follower
# blocks, and if not leader, execute follower stuff
# instead use locks to see if the leader stuff is done, and then can do follower stuff rather than waiting
contenders = None
while True:
try:
contenders = election.contenders()
except:
# retry in case election is not defined
time.sleep(1)
if contenders and contenders[0] == id:
print(f"I {id} am the leader now!")
break
elif contenders:
# Do the Follower stuff
print(f"I {id} am the follower. {contenders}")
time.sleep(5) # Check every 5 seconds
zk = KazooClient(hosts='127.0.0.1:2181')
zk.start()
zk.ensure_path("kingdom/election")
id = "node" + str(random.randint(1, 1000))
# Start the leader check in a non-blocking way, and execute follower code if leader check is false
import threading
leader_thread = threading.Thread(target=do_follower_stuff)
leader_thread.start()
while True:
# election.run blocks the thread, until elected
# Once elected, the thread becomes leader until the func=whoIsKing returns,
# this thread surrenders the leadership, once the func=whoIsKing returns
# rejoin the leadership race, after surrendering the leadership, perpetually
election = zk.Election("/kingdom/election", id)
election.run(func=leader_callback)```