gpt4 book ai didi

apache-zookeeper - Apache 馆长 LeaderSelector : How to avoid giving up leadership by not exiting from takeLeadership() method?

转载 作者:行者123 更新时间:2023-12-02 01:47:08 28 4
gpt4 key购买 nike

I'm trying to implement a simple leader election based system where my main business logic of the application runs on the elected leader node.作为获得领导地位的一部分,主要业务逻辑启动各种其他服务。我正在使用 Apache Curator LeaderSelector 配方来实现领导者选择过程。

在我的系统中,被选为领导者的节点保持领导地位,直到失败迫使另一个领导者被选出。换句话说,一旦我获得了领导权,我就不想放弃它。

根据 Curator LeaderSelection 文档,当 takeLeadership() 方法返回时,领导权将被放弃。我想避免它,我现在只是通过引入等待循环来阻止返回。

我的问题是:

  1. 这是实现领导力的正确方式吗?
  2. 等待循环(如下面的代码示例所示)是阻塞的正确方式吗?

    public class MainBusinessLogic extends LeaderSelectorListenerAdapter {      
    private static final String ZK_PATH_LEADER_ROOT = "/some-path";
    private final CuratorFramework client;
    private final LeaderSelector leaderSelector;

    public MainBusinessLogic() {
    client = CuratorService.getInstance().getCuratorFramework();
    leaderSelector = new LeaderSelector(client, ZK_PATH_LEADER_ROOT, this);
    leaderSelector.autoRequeue();
    leaderSelector.start();
    }

    @Override
    public void takeLeadership(CuratorFramework client) throws IOException {
    // Start various other internal services...
    ServiceA serviceA = new ServiceA(...);
    ServiceB serviceB = new ServiceB(...);
    ...
    ...
    serviceA.start();
    serviceB.start();
    ...
    ...

    // We are done but need to keep leadership to this instance, else all the business
    // logic and services will start on another node.
    // Is this the right way to prevent relinquishing leadership???
    while (true) {
    synchronized (this) {
    try {
    wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }

最佳答案

LeaderLatch 而不是 wait(),你可以这样做:

Thread.currentThread().join();

但是,是的,这是正确的。

顺便说一句 - 如果您喜欢不同的方法,您可以将 LeaderLatch 与 LeaderLatchListener 一起使用。

关于apache-zookeeper - Apache 馆长 LeaderSelector : How to avoid giving up leadership by not exiting from takeLeadership() method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25030262/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com