一、引入jar包
<!--引入zk依赖-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.6.1</version>
<!--排除这个slf4j-log4j12-->
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入curator依赖-->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.2.0</version>
</dependency>
二、使用示例
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import java.io.IOException;
public class LeaderLatchTest {
private static final String PATH = "/leader";
private static final String APP_ID = "001";
public static void main(String[] args) throws IOException {
CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));
client.start();
LeaderLatch leaderLatch = new LeaderLatch(client, PATH, APP_ID);
leaderLatch.addListener(new LeaderLatchListener() {
/**
* isLeader 中的方法会在实例被选为主节点后被执行, 而notLeader中的不会被执行
* 如果主节点被失效, 会进行重新选主
*/
@Override
public void isLeader() {
System.out.println("======= [LeaderLatch]我是主节点, app_id={" + leaderLatch.getId() + "} =========");
}
/**
* 当丢失leader的时候被执行
*/
@Override
public void notLeader() {
System.out.println("======= [LeaderLatch]我不是主节点, app_id={" + leaderLatch.getId() + "} =========");
}
});
try {
leaderLatch.start();
while (true) {
Thread.sleep(10000);
System.out.println("======= " + leaderLatch.getLeader() + " ==========");
}
} catch (Exception e) {
e.printStackTrace();
leaderLatch.close();
client.close();
}
}
}
温馨提示:在idea中更改APP_ID,开启多个main并行执行,即可模拟集群选举效果。