我正在使用 Apache Curator 库对 Zookeeper 进行领导选举。我的应用程序代码部署在多台机器上,我只需要从一台机器上执行我的代码,这就是为什么我在 zookeeper 上进行领导选举,以便我可以检查我是否是领导者,然后执行此代码。
下面是我的LeaderElectionExecutor
课程,它确保每个应用程序都有一个 Curator 实例
public class LeaderElectionExecutor {
private ZookeeperClient zookClient;
private static final String LEADER_NODE = "/testleader";
private static class Holder {
static final LeaderElectionExecutor INSTANCE = new LeaderElectionExecutor();
}
public static LeaderElectionExecutor getInstance() {
return Holder.INSTANCE;
}
private LeaderElectionExecutor() {
try {
String hostname = Utils.getHostName();
String nodes = "host1:2181,host2:2181;
zookClient = new ZookeeperClient(nodes, LEADER_NODE, hostname);
zookClient.start();
// added sleep specifically for the leader to get selected
// since I cannot call isLeader method immediately after starting the latch
TimeUnit.MINUTES.sleep(1);
} catch (Exception ex) {
// logging error
System.exit(1);
}
}
public ZookeeperClient getZookClient() {
return zookClient;
}
}
下面是我的ZookeeperClient
代码 -
// can this class be improved in any ways?
public class ZookeeperClient {
private CuratorFramework client;
private String latchPath;
private String id;
private LeaderLatch leaderLatch;
public ZookeeperClient(String connString, String latchPath, String id) {
client = CuratorFrameworkFactory.newClient(connString, new ExponentialBackoffRetry(1000, Integer.MAX_VALUE));
this.id = id;
this.latchPath = latchPath;
}
public void start() throws Exception {
client.start();
leaderLatch = new LeaderLatch(client, latchPath, id);
leaderLatch.start();
}
public boolean isLeader() {
return leaderLatch.hasLeadership();
}
public Participant currentLeader() throws Exception {
return leaderLatch.getLeader();
}
public void close() throws IOException {
leaderLatch.close();
client.close();
}
public CuratorFramework getClient() {
return client;
}
public String getLatchPath() {
return latchPath;
}
public String getId() {
return id;
}
public LeaderLatch getLeaderLatch() {
return leaderLatch;
}
}
现在在我的应用程序中,我正在使用这样的代码 -
public void method01() {
ZookeeperClient zookClient = LeaderElectionExecutor.getInstance().getZookClient();
if (zookClient.isLeader()) {
// do something
}
}
public void method02() {
ZookeeperClient zookClient = LeaderElectionExecutor.getInstance().getZookClient();
if (zookClient.isLeader()) {
// do something
}
}
问题陈述:-
在 Curator 库中 -isLeader()
启动闩锁后立即调用将不起作用。领导者被选中需要时间。仅因为这个原因,我在我的LeaderElectionExecutor
代码中添加了 1 分钟的睡眠时间,它工作正常,但我想这不是正确的方法。
有没有更好的方法来做到这一点?记住这一点,我需要一种方法来检查我是否是领导者,然后执行这段代码。我不能用一个方法做所有事情,所以我需要isLeader
从不同的类和方法中调用方法来检查我是否是领导者,然后只执行这段代码。
我正在使用 Zookeeper 3.4.5 和 Curator 1.7.1 版本。