Apache Cutator Leaderselector:如何避免通过从Takeleadership()方法中退出来放弃领导?
-
21-12-2019 - |
题
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 Curater Leaderselector配方来实现领导者选择过程。
在我的系统中,作为领导者被选中的节点会使领导能力保持在失败迫使另一个要选择的领导者。换句话说,一旦我得到领导,我不想放弃它。
根据策展人领导文档,当takeLeadership()
方法返回时,领导能够放弃。我想避免它,我现在就是通过引入等待循环来阻止返回。
我的问题是:
- 是实现领导力的正确方法?
-
是等待循环(如下面的代码示例所示)块的正确方法?
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(); } } } } }
解决方案
ripentlatchinstead的等待(),您可以执行以下操作:
Thread.currentThread().join();
.
但是,是的,这是正确的。
btw - 如果您更喜欢不同的方法,您可以使用带索引路标的排队暂存。
不隶属于 StackOverflow