最近在项目中使用了zk来实现主节点的选举,下面主要介绍下
curator
中提供的leader selector模块
Apache Curator
Apache Curator是Apache提供的zookeeper客户端,提供了诸如zk节点操作,分布式锁,通知,订阅,注册发现选举等操作。
选举客户端
继承LeaderSelectorListenerAdapter
,实现LeaderSelectorListenerAdapter#takeLeadership
方法,该方法由curator框架负责在当前客户端节点成为leader
之后回调。
需要注意,LeaderSelectorListenerAdapter#takeLeadership
方法推出则代表当前节点归还leader
权限,当你希望该节点长期持有leader
权限时,请不要退出该方法。
leaderSelector.autoRequeue()
会在当前节点归还了leader
权限后,重新将当前节点竞选队列。
简单的java案例:
public class SelectorClient extends LeaderSelectorListenerAdapter implements Closeable{
private final LeaderSelector leaderSelector;
private final String selectorPath = "/selector/leader";
private boolean leader = false;
private int waitSecond = 5;
@Autowired
public SelectorClient(CuratorFramework curatorFramework) {
this.leaderSelector = new LeaderSelector(curatorFramework, selectorPath, this);
this.leaderSelector.autoRequeue();
}
@Override
public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
leader = true;
try {
TimeUnit.SECONDS.sleep(waitSecond);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
leader = false;
}
}
@Override
public void close() throws IOException {
this.leaderSelector.close();
}
public void start() {
this.leaderSelector.start();
}
public boolean isLeader() {
return leader;
}
public void giveBack() {
this.leaderSelector.requeue();
}
}
启动选举
- 启动curator框架:
CuratorFramework.start()
- 启动使用第一步
CuratorFramework
构建的SelectorClient
:selector.start()