概述
利用zookeeper来进行选主,可以使用apache curator framework,它给我们封装了两种选主工具,它们分别是LeaderSelector和LeaderLatch。它们各自的应用场景不一样,LeaderSelector应用于那些需要频繁变主的情况,而LeaderLatch则用于不频繁变主的情况。今天我们主要介绍LeaderLatch。
原理
LeaderLatch的实现原理其实是利用了zookeeper的临时有序节点来实现,比如我们在/leader目录下创建临时有序的节点,那么应用第一个实例创建类似/leader/node-0,第二个实例创建类似/leader/node-1(实际目录名不是叫这个,这里只是打个比方),那么LeaderLatch会选择序号最小的zookeeper节点作为主节点,每个从节点实例都会监听前一个比自己小的znode的事件,一旦比自己小的zookeeper节点发生变化,则立马检测自身是否可成为主节点。
实现
引入maven依赖
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<!--需要和你zookeeper的版本一致-->
<version>3.4.14</version>
</dependency>
初始化CuratorFramework Client
public void initClient() {
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString("127.0.0.1:2181")
.retryPolicy(new RetryNTimes(1, 1000))
.connectionTimeoutMs(30 * 1000)
.sessionTimeoutMs(60 * 1000);
client = builder.build();
client.start();
}
创建LeaderLatch实例
public void initLeaderLatch() throws Exception {
//participantId 为选举者ID,LeaderLatch.CloseMode.NOTIFY_LEADER 模式在失主的时候会回调下notLeader方法
LeaderLatch leaderLatch = new LeaderLatch(client, "/leader", "participantId", LeaderLatch.CloseMode.NOTIFY_LEADER);
leaderLatch.addListener(new LeaderLatchListener() {
@Override
public void isLeader() {
System.out.print("I am leader.");
}
@Override
public void notLeader() {
System.out.print("I am not leader.");
}
});
leaderLatch.start();
}
关闭资源释放连接
public void close() throws IOException {
leaderLatch.close();
client.close();
}
检查自己是否还在选民列表中
可以定时的检查一下应用实例是否还在选民列表中,如果已不在选民列表中,可先关闭连接,然后再重新初始化client和LeaderLatch,维持应用集群状态与zookeeper上的临时有序节点的最终一致性。
/**
* 检查当前进程是否还在选民列表中,不在的话,可以进行重连,使得自己重新回到选民列表中
*/
public boolean checkMeInParticipants() throws Exception {
boolean result = false;
Collection<Participant> participants =
participants = this.leaderLatch.getParticipants();
for (Participant participant : participants) {
if ("participantId".equals(participant.getId())) {
result = true;
break;
}
}
return result;
}