3

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();
            }
          }
        }
      }
    }
    
4

1 回答 1

2

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

Thread.currentThread().join();

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

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

于 2014-07-30T13:40:20.687 回答