找回密码
 立即注册
首页 业界区 业界 zk基础—5.Curator的使用与剖析

zk基础—5.Curator的使用与剖析

芮梦月 2025-6-2 22:58:35
大纲
1.基于Curator进行基本的zk数据操作
2.基于Curator实现集群元数据管理
3.基于Curator实现HA主备自动切换
4.基于Curator实现Leader选举
5.基于Curator实现分布式Barrier
6.基于Curator实现分布式计数器
7.基于Curator实现zk的节点和子节点监听机制
8.基于Curator创建客户端实例的源码分析
9.Curator在启动时是如何跟zk建立连接的
10.基于Curator进行增删改查节点的源码分析
11.基于Curator的节点监听回调机制的实现源码
12.基于Curator的Leader选举机制的实现源码
 
1.基于Curator进行基本的zk数据操作
Guava is to Java what Curator is to ZooKeeper,引入依赖如下:
  1. <dependencies>
  2.     <dependency>
  3.         <groupId>org.apache.curator</groupId>
  4.         curator-framework</artifactId>
  5.         <version>2.12.0</version>
  6.     </dependency>
  7.     <dependency>
  8.         <groupId>org.apache.curator</groupId>
  9.         curator-recipes</artifactId>
  10.         <version>2.12.0</version>
  11.     </dependency>
  12. </dependencies>
复制代码
Curator实现对znode进行增删改查的示例如下,其中CuratorFramework代表一个客户端实例。注意:可以通过creatingParentsIfNeeded()方法进行指定节点的级联创建。
  1. public class CrudDemo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);
  5.         client.start();//启动客户端并建立连接
  6.      
  7.         System.out.println("已经启动Curator客户端");
  8.         client.create()
  9.             .creatingParentsIfNeeded()//进行级联创建
  10.             .withMode(CreateMode.PERSISTENT)//指定节点类型
  11.             .forPath("/my/path", "10".getBytes());//增
  12.         byte[] dataBytes = client.getData().forPath("/my/path");//查
  13.         System.out.println(new String(dataBytes));
  14.         client.setData().forPath("/my/path", "11".getBytes());//改
  15.         dataBytes = client.getData().forPath("/my/path");
  16.         System.out.println(new String(dataBytes));
  17.         List<String> children = client.getChildren().forPath("/my");//查
  18.         System.out.println(children);
  19.         client.delete().forPath("/my/path");//删
  20.         Thread.sleep(Integer.MAX_VALUE);
  21.     }
  22. }
复制代码
 
2.基于Curator实现集群元数据管理
Curator可以操作zk。比如自研了一套分布式系统类似于Kafka、Canal,想把集群运行的核心元数据都放到zk里去。此时就可以通过Curator创建一些znode,往里面写入对应的值。
 
写入的值推荐用json格式,比如Kafka就是往zk写json格式数据。这样,其他客户端在需要的时候,就可以从里面读取出集群元数据了。
 
3.基于Curator实现HA主备自动切换
HDFS、Kafka、Canal都使用了zk进行Leader选举,所以可以基于Curator实现HA主备自动切换。
 
HDFS的NameNode是可以部署HA架构的,有主备两台机器。如果主机器宕机了,备用的机器可以感知到并选举为Leader,这样备用的机器就可以作为新的NameNode对外提供服务。
 
Kafka里的Controller负责管理整个集群的协作,Kafka中任何一个Broker都可以变成Controller,类似于Leader的角色。
 
Canal也会部署主备两台机器,主机器挂掉了,备用机器就可以跟上去。
 
4.基于Curator实现Leader选举
(1)Curator实现Leader选举的第一种方式之LeaderLatch
(2)Curator实现Leader选举的第二种方式之LeaderSelector
 
(1)Curator实现Leader选举的第一种方式之LeaderLatch
通过Curator的LeaderLatch来实现Leader选举:
  1. public class LeaderLatchDemo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);
  5.         client.start();
  6.         
  7.         //"/leader/latch"这其实是一个znode顺序节点
  8.         LeaderLatch leaderLatch = new LeaderLatch(client, "/leader/latch");
  9.         leaderLatch.start();
  10.         leaderLatch.await();//直到等待他成为Leader再往后执行
  11.         //类似于HDFS里,两台机器,其中一台成为了Leader就开始工作
  12.         //另外一台机器可以通过await阻塞在这里,直到Leader挂了,自己就会成为Leader继续工作
  13.         Boolean hasLeaderShip = leaderLatch.hasLeadership();//判断是否成为Leader
  14.         System.out.println("是否成为leader:" + hasLeaderShip);
  15.         Thread.sleep(Integer.MAX_VALUE);
  16.     }
  17. }
复制代码
(2)Curator实现Leader选举的第二种方式之LeaderSelector
通过Curator的LeaderSelector来实现Leader选举如下:其中,LeaderSelector有两个监听器,可以关注连接状态。
  1. public class LeaderSelectorDemo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);
  5.         client.start();
  6.         LeaderSelector leaderSelector = new LeaderSelector(
  7.             client,
  8.             "/leader/election",
  9.             new LeaderSelectorListener() {
  10.                 public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
  11.                     System.out.println("你已经成为了Leader......");
  12.                     //在这里干Leader所有的事情,此时方法不能退出
  13.                     Thread.sleep(Integer.MAX_VALUE);
  14.                 }
  15.                
  16.                 public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
  17.                     System.out.println("连接状态的变化,已经不是Leader......");
  18.                     if (connectionState.equals(ConnectionState.LOST)) {
  19.                         throw new CancelLeadershipException();
  20.                     }
  21.                 }
  22.             }
  23.         );
  24.         leaderSelector.start();//尝试和其他节点在节点"/leader/election"上进行竞争成为Leader
  25.         Thread.sleep(Integer.MAX_VALUE);
  26.     }
  27. }
复制代码
 
5.基于Curator实现的分布式Barrier
(1)分布式Barrier
(2)分布式双重Barrier
 
(1)分布式Barrier
很多台机器都可以创建一个Barrier,此时它们都被阻塞了。除非满足一个条件(setBarrier()或removeBarrier()),才能不再阻塞它们。
  1. //DistributedBarrier
  2. public class DistributedBarrierDemo {
  3.     public static void main(String[] args) throws Exception {
  4.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  5.         CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);
  6.         client.start();
  7.         DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");
  8.         barrier.waitOnBarrier();
  9.     }
  10. }
复制代码
(2)分布式双重Barrier
  1. //DistributedDoubleBarrier
  2. public class DistributedDoubleBarrierDemo {
  3.     public static void main(String[] args) throws Exception {
  4.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  5.         CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);
  6.         client.start();
  7.         DistributedDoubleBarrier doubleBarrier = new DistributedDoubleBarrier(client, "/barrier/double", 10);
  8.         doubleBarrier.enter();//每台机器都会阻塞在enter这里
  9.         //直到10台机器都调用了enter,就会从enter这里往下执行
  10.         //此时可以做一些计算任务
  11.         doubleBarrier.leave();//每台机器都会阻塞在leave这里,直到10台机器都调用了leave
  12.         //此时就可以继续往下执行
  13.     }
  14. }
复制代码
 
6.基于Curator实现分布式计数器
如果真的要实现分布式计数器,最好用Redis来实现。因为Redis的并发量更高,性能更好,功能更加的强大,而且还可以使用lua脚本嵌入进去实现复杂的业务逻辑。但是Redis天生的异步同步机制,存在机器宕机导致的数据不同步风险。然而zk在ZAB协议下的数据同步机制,则不会出现宕机导致数据不同步的问题。
  1. //SharedCount:通过一个节点的值来实现
  2. public class SharedCounterDemo {
  3.     public static void main(String[] args) throws Exception {
  4.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  5.         CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);
  6.         client.start();
  7.         SharedCount sharedCount = new SharedCount(client, "/shared/count", 0);
  8.         sharedCount.start();
  9.         sharedCount.addListener(new SharedCountListener() {
  10.             public void countHasChanged(SharedCountReader sharedCountReader, int i) throws Exception {
  11.                 System.out.println("分布式计数器变化了......");
  12.             }
  13.             public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
  14.                 System.out.println("连接状态变化了.....");
  15.             }
  16.         });
  17.         Boolean result = sharedCount.trySetCount(1);
  18.         System.out.println(sharedCount.getCount());
  19.     }
  20. }
复制代码
 
7.基于Curator实现zk的节点和子节点监听机制
(1)基于Curator实现zk的子节点监听机制
(2)基于Curator实现zk的节点数据监听机制
 
我们使用zk主要用于:
一.对元数据进行增删改查、监听元数据的变化
二.进行Leader选举
 
有三种类型的节点可以监听:
一.子节点监听PathCache
二.节点监听NodeCache
三.整个节点以下的树监听TreeCache
 
(1)基于Curator实现zk的子节点监听机制
下面是PathCache实现的子节点监听示例:
  1. public class PathCacheDemo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);
  5.         client.start();
  6.         PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/cluster", true);
  7.         //cache就是把zk里的数据缓存到客户端里来
  8.         //可以针对这个缓存的数据加监听器,去观察zk里的数据的变化
  9.         pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
  10.             public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
  11.             }
  12.         });
  13.         pathChildrenCache.start();
  14.     }
  15. }
复制代码
(2)基于Curator实现zk的节点数据监听机制
下面是NodeCache实现的节点监听示例:
  1. public class NodeCacheDemo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         final CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", 5000, 3000, retryPolicy);
  5.         client.start();
  6.         final NodeCache nodeCache = new NodeCache(client, "/cluster");
  7.         nodeCache.getListenable().addListener(new NodeCacheListener() {
  8.             public void nodeChanged() throws Exception {
  9.                 Stat stat = client.checkExists().forPath("/cluster");
  10.                 if (stat == null) {
  11.                     
  12.                 } else {
  13.                     nodeCache.getCurrentData();
  14.                 }
  15.             }
  16.         });
  17.         nodeCache.start();
  18.     }
  19. }
复制代码
 
8.基于Curator创建客户端实例的源码分析
(1)创建CuratorFramework实例使用了构造器模式
(2)创建CuratorFramework实例会初始化CuratorZooKeeperClient实例
 
(1)创建CuratorFramework实例使用了构造器模式
CuratorFrameworkFactory.newClient()方法使用了构造器模式。首先通过builder()方法创建出Builder实例对象,然后把参数都设置成Builder实例对象的属性,最后通过build()方法把Builder实例对象传入目标类的构造方法中。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.       RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.       CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.               "127.0.0.1:2181",//zk的地址
  6.               5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.               3000,//连接zk时的超时时间
  8.               retryPolicy
  9.       );
  10.       client.start();
  11.       System.out.println("已经启动Curator客户端");
  12.     }
  13. }
  14. public class CuratorFrameworkFactory {
  15.     //创建CuratorFramework实例使用了构造器模式
  16.     public static CuratorFramework newClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy) {
  17.         return builder().
  18.             connectString(connectString).
  19.             sessionTimeoutMs(sessionTimeoutMs).
  20.             connectionTimeoutMs(connectionTimeoutMs).
  21.             retryPolicy(retryPolicy).
  22.             build();
  23.     }
  24.     ...
  25.     public static Builder builder() {
  26.         return new Builder();
  27.     }
  28.    
  29.     public static class Builder {
  30.         ...
  31.         private EnsembleProvider ensembleProvider;
  32.         private int sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS;
  33.         private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS;
  34.         private RetryPolicy retryPolicy;
  35.         ...
  36.         public Builder connectString(String connectString) {
  37.             ensembleProvider = new FixedEnsembleProvider(connectString);
  38.             return this;
  39.         }
  40.         
  41.         public Builder sessionTimeoutMs(int sessionTimeoutMs) {
  42.             this.sessionTimeoutMs = sessionTimeoutMs;
  43.             return this;
  44.         }
  45.         
  46.         public Builder connectionTimeoutMs(int connectionTimeoutMs) {
  47.             this.connectionTimeoutMs = connectionTimeoutMs;
  48.             return this;
  49.         }
  50.         
  51.         public Builder retryPolicy(RetryPolicy retryPolicy) {
  52.             this.retryPolicy = retryPolicy;
  53.             return this;
  54.         }
  55.         ...
  56.         public CuratorFramework build() {
  57.             return new CuratorFrameworkImpl(this);
  58.         }
  59.     }
  60.     ...
  61. }
  62. public class CuratorFrameworkImpl implements CuratorFramework {
  63.     ...
  64.     public CuratorFrameworkImpl(CuratorFrameworkFactory.Builder builder) {
  65.         ZookeeperFactory localZookeeperFactory = makeZookeeperFactory(builder.getZookeeperFactory());
  66.         this.client = new CuratorZookeeperClient(
  67.             localZookeeperFactory,
  68.             builder.getEnsembleProvider(),
  69.             builder.getSessionTimeoutMs(),
  70.             builder.getConnectionTimeoutMs(),
  71.             builder.getWaitForShutdownTimeoutMs(),
  72.             new Watcher() {//这里注册了一个zk的watcher
  73.                 @Override
  74.                 public void process(WatchedEvent watchedEvent) {
  75.                     CuratorEvent event = new CuratorEventImpl(CuratorFrameworkImpl.this, CuratorEventType.WATCHED, watchedEvent.getState().getIntValue(), unfixForNamespace(watchedEvent.getPath()), null, null, null, null, null, watchedEvent, null, null);
  76.                     processEvent(event);
  77.                 }
  78.             },
  79.             builder.getRetryPolicy(),
  80.             builder.canBeReadOnly(),
  81.             builder.getConnectionHandlingPolicy()
  82.         );
  83.         ...
  84.     }
  85.     ...
  86. }
复制代码
(2)创建CuratorFramework实例会初始化CuratorZooKeeperClient实例
CuratorFramework实例代表了一个zk客户端,CuratorFramework初始化时会初始化一个CuratorZooKeeperClient实例。
 
CuratorZooKeeperClient是Curator封装ZooKeeper的客户端。
 
初始化CuratorZooKeeperClient时会传入一个Watcher监听器。
 
所以CuratorFrameworkFactory的newClient()方法的主要工作是:初始化CuratorFramework -> 初始化CuratorZooKeeperClient -> 初始化ZookeeperFactory + 注册一个Watcher。
 
客户端发起与zk的连接,以及注册Watcher监听器,则是由CuratorFramework的start()方法触发的。
 
9.Curator启动时是如何跟zk建立连接的
ConnectionStateManager的start()方法会启动一个线程处理eventQueue。eventQueue里存放了与zk的网络连接变化事件,eventQueue收到这种事件便会通知ConnectionStateListener。
 
CuratorZookeeperClient的start()方法会初始化好原生zk客户端,和zk服务器建立一个TCP长连接,而且还会注册一个ConnectionState类型的Watcher监听器,以便能收到zk服务端发送的通知事件。
  1. public class CuratorFrameworkImpl implements CuratorFramework {
  2.     private final CuratorZookeeperClient client;
  3.     private final ConnectionStateManager connectionStateManager;
  4.     private volatile ExecutorService executorService;
  5.     ...
  6.     public CuratorFrameworkImpl(CuratorFrameworkFactory.Builder builder) {
  7.         ...
  8.         this.client = new CuratorZookeeperClient(...);
  9.         connectionStateManager = new ConnectionStateManager(this, builder.getThreadFactory(),
  10.             builder.getSessionTimeoutMs(),
  11.             builder.getConnectionHandlingPolicy().getSimulatedSessionExpirationPercent(),
  12.             builder.getConnectionStateListenerDecorator()
  13.         );
  14.         ...
  15.     }
  16.     ...
  17.     @Override
  18.     public void start() {
  19.         log.info("Starting");
  20.         if (!state.compareAndSet(CuratorFrameworkState.LATENT, CuratorFrameworkState.STARTED)) {
  21.             throw new IllegalStateException("Cannot be started more than once");
  22.         }
  23.         ...
  24.         //1.启动一个线程监听和zk网络连接的变化事件
  25.         connectionStateManager.start();
  26.         //2.添加一个监听器监听和zk网络连接的变化
  27.         final ConnectionStateListener listener = new ConnectionStateListener() {
  28.             @Override
  29.             public void stateChanged(CuratorFramework client, ConnectionState newState) {
  30.                 if (ConnectionState.CONNECTED == newState || ConnectionState.RECONNECTED == newState) {
  31.                     logAsErrorConnectionErrors.set(true);
  32.                 }
  33.             }
  34.             @Override
  35.             public boolean doNotDecorate() {
  36.                 return true;
  37.             }
  38.         };
  39.         this.getConnectionStateListenable().addListener(listener);
  40.         //3.创建原生zk客户端
  41.         client.start();
  42.         //4.创建一个线程池,执行后台的操作
  43.         executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
  44.         executorService.submit(new Callable<Object>() {
  45.             @Override
  46.             public Object call() throws Exception {
  47.                 backgroundOperationsLoop();
  48.                 return null;
  49.             }
  50.         });
  51.         if (ensembleTracker != null) {
  52.             ensembleTracker.start();
  53.         }
  54.         log.info(schemaSet.toDocumentation());
  55.     }
  56.     ...
  57. }
  58. public class ConnectionStateManager implements Closeable {
  59.     private final ExecutorService service;
  60.     private final BlockingQueue<ConnectionState> eventQueue = new ArrayBlockingQueue<ConnectionState>(QUEUE_SIZE);
  61.     ...
  62.     public ConnectionStateManager(CuratorFramework client, ThreadFactory threadFactory, int sessionTimeoutMs, int sessionExpirationPercent, ConnectionStateListenerDecorator connectionStateListenerDecorator) {
  63.         ...
  64.         service = Executors.newSingleThreadExecutor(threadFactory);
  65.         ...
  66.     }
  67.     ...
  68.     public void start() {
  69.         Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");
  70.         //启动一个线程
  71.         service.submit(
  72.             new Callable<Object>() {
  73.                 @Override
  74.                 public Object call() throws Exception {
  75.                     processEvents();
  76.                     return null;
  77.                 }
  78.             }
  79.         );
  80.     }
  81.    
  82.     private void processEvents() {
  83.         while (state.get() == State.STARTED) {
  84.             int useSessionTimeoutMs = getUseSessionTimeoutMs();
  85.             long elapsedMs = startOfSuspendedEpoch == 0 ? useSessionTimeoutMs / 2 : System.currentTimeMillis() - startOfSuspendedEpoch;
  86.             long pollMaxMs = useSessionTimeoutMs - elapsedMs;
  87.             final ConnectionState newState = eventQueue.poll(pollMaxMs, TimeUnit.MILLISECONDS);
  88.             if (newState != null) {
  89.                 if (listeners.size() == 0) {
  90.                     log.warn("There are no ConnectionStateListeners registered.");
  91.                 }
  92.                 listeners.forEach(listener -> listener.stateChanged(client, newState));
  93.             } else if (sessionExpirationPercent > 0) {
  94.                 synchronized(this) {
  95.                     checkSessionExpiration();
  96.                 }
  97.             }
  98.         }
  99.     }
  100.     ...
  101. }
  102. public class CuratorZookeeperClient implements Closeable {
  103.     private final ConnectionState state;
  104.     ...
  105.     public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider,
  106.             int sessionTimeoutMs, int connectionTimeoutMs, int waitForShutdownTimeoutMs, Watcher watcher,
  107.             RetryPolicy retryPolicy, boolean canBeReadOnly, ConnectionHandlingPolicy connectionHandlingPolicy) {
  108.         ...
  109.         state = new ConnectionState(zookeeperFactory, ensembleProvider, sessionTimeoutMs, connectionTimeoutMs, watcher, tracer, canBeReadOnly, connectionHandlingPolicy);
  110.         ...
  111.     }
  112.     ...
  113.     public void start() throws Exception {
  114.         log.debug("Starting");
  115.         if (!started.compareAndSet(false, true)) {
  116.             throw new IllegalStateException("Already started");
  117.         }
  118.         state.start();
  119.     }
  120.     ...
  121. }
  122. class ConnectionState implements Watcher, Closeable {
  123.     private final HandleHolder zooKeeper;
  124.     ConnectionState(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider,
  125.             int sessionTimeoutMs, int connectionTimeoutMs, Watcher parentWatcher,
  126.             AtomicReference<TracerDriver> tracer, boolean canBeReadOnly, ConnectionHandlingPolicy connectionHandlingPolicy) {
  127.         this.ensembleProvider = ensembleProvider;
  128.         this.sessionTimeoutMs = sessionTimeoutMs;
  129.         this.connectionTimeoutMs = connectionTimeoutMs;
  130.         this.tracer = tracer;
  131.         this.connectionHandlingPolicy = connectionHandlingPolicy;
  132.         if (parentWatcher != null) {
  133.             parentWatchers.offer(parentWatcher);
  134.         }
  135.         //把自己作为Watcher注册给HandleHolder
  136.         zooKeeper = new HandleHolder(zookeeperFactory, this, ensembleProvider, sessionTimeoutMs, canBeReadOnly);
  137.     }
  138.     ...
  139.     void start() throws Exception {
  140.         log.debug("Starting");
  141.         ensembleProvider.start();
  142.         reset();
  143.     }
  144.    
  145.     synchronized void reset() throws Exception {
  146.         log.debug("reset");
  147.         instanceIndex.incrementAndGet();
  148.         isConnected.set(false);
  149.         connectionStartMs = System.currentTimeMillis();
  150.         //创建客户端与zk的连接
  151.         zooKeeper.closeAndReset();
  152.         zooKeeper.getZooKeeper();//initiate connection
  153.     }
  154.     ...
  155. }
  156. class HandleHolder {
  157.     private final ZookeeperFactory zookeeperFactory;
  158.     private final Watcher watcher;
  159.     private final EnsembleProvider ensembleProvider;
  160.     private final int sessionTimeout;
  161.     private final boolean canBeReadOnly;
  162.     private volatile Helper helper;
  163.     ...
  164.     HandleHolder(ZookeeperFactory zookeeperFactory, Watcher watcher, EnsembleProvider ensembleProvider, int sessionTimeout, boolean canBeReadOnly) {
  165.         this.zookeeperFactory = zookeeperFactory;
  166.         this.watcher = watcher;
  167.         this.ensembleProvider = ensembleProvider;
  168.         this.sessionTimeout = sessionTimeout;
  169.         this.canBeReadOnly = canBeReadOnly;
  170.     }
  171.    
  172.     private interface Helper {
  173.         ZooKeeper getZooKeeper() throws Exception;
  174.         String getConnectionString();
  175.         int getNegotiatedSessionTimeoutMs();
  176.     }
  177.    
  178.     ZooKeeper getZooKeeper() throws Exception {
  179.         return (helper != null) ? helper.getZooKeeper() : null;
  180.     }
  181.    
  182.     void closeAndReset() throws Exception {
  183.         internalClose(0);
  184.         helper = new Helper() {
  185.             private volatile ZooKeeper zooKeeperHandle = null;
  186.             private volatile String connectionString = null;
  187.             @Override
  188.             public ZooKeeper getZooKeeper() throws Exception {
  189.                 synchronized(this) {
  190.                     if (zooKeeperHandle == null) {
  191.                         connectionString = ensembleProvider.getConnectionString();
  192.                         //创建和zk的连接,初始化变量zooKeeperHandle
  193.                         zooKeeperHandle = zookeeperFactory.newZooKeeper(connectionString, sessionTimeout, watcher, canBeReadOnly);
  194.                     }
  195.                     ...
  196.                     return zooKeeperHandle;
  197.                 }
  198.             }
  199.             @Override
  200.             public String getConnectionString() {
  201.                 return connectionString;
  202.             }
  203.             @Override
  204.             public int getNegotiatedSessionTimeoutMs() {
  205.                 return (zooKeeperHandle != null) ? zooKeeperHandle.getSessionTimeout() : 0;
  206.             }
  207.         };
  208.     }
  209.     ...
  210. }
  211. //创建客户端与zk的连接
  212. public class DefaultZookeeperFactory implements ZookeeperFactory {
  213.     @Override
  214.     public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception {
  215.         return new ZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly);
  216.     }
  217. }
复制代码
 
10.基于Curator进行增删改查节点的源码分析
(1)基于Curator创建znode节点
(2)基于Curator查询znode节点
(3)基于Curator修改znode节点
(4)基于Curator删除znode节点
 
Curator的CURD操作,底层都是通过调用zk原生的API来完成的。
 
(1)基于Curator创建znode节点
创建节点也使用了构造器模式:首先通过CuratorFramework的create()方法创建一个CreateBuilder实例,然后通过CreateBuilder的withMode()等方法设置CreateBuilder的变量,最后通过CreateBuilder的forPath()方法 + 重试调用来创建znode节点。
 
创建节点时会调用CuratorFramework的getZooKeeper()方法获取zk客户端实例,之后就是通过原生zk客户端的API去创建节点了。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端");
  12.         //创建节点
  13.         client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/my/path", "100".getBytes());
  14.     }
  15. }
  16. public class CuratorFrameworkImpl implements CuratorFramework {
  17.     ...
  18.     @Override
  19.     public CreateBuilder create() {
  20.         checkState();
  21.         return new CreateBuilderImpl(this);
  22.     }
  23.     ...
  24. }
  25. public class CreateBuilderImpl implements CreateBuilder, CreateBuilder2, BackgroundOperation<PathAndBytes>, ErrorListenerPathAndBytesable<String> {
  26.     private final CuratorFrameworkImpl client;
  27.     private CreateMode createMode;
  28.     private Backgrounding backgrounding;
  29.     private boolean createParentsIfNeeded;
  30.     ...
  31.     CreateBuilderImpl(CuratorFrameworkImpl client) {
  32.         this.client = client;
  33.         createMode = CreateMode.PERSISTENT;
  34.         backgrounding = new Backgrounding();
  35.         acling = new ACLing(client.getAclProvider());
  36.         createParentsIfNeeded = false;
  37.         createParentsAsContainers = false;
  38.         compress = false;
  39.         setDataIfExists = false;
  40.         storingStat = null;
  41.         ttl = -1;
  42.     }
  43.    
  44.     @Override
  45.     public String forPath(final String givenPath, byte[] data) throws Exception {
  46.         if (compress) {
  47.             data = client.getCompressionProvider().compress(givenPath, data);
  48.         }
  49.         final String adjustedPath = adjustPath(client.fixForNamespace(givenPath, createMode.isSequential()));
  50.         List aclList = acling.getAclList(adjustedPath);
  51.         client.getSchemaSet().getSchema(givenPath).validateCreate(createMode, givenPath, data, aclList);
  52.         String returnPath = null;
  53.         if (backgrounding.inBackground()) {
  54.             pathInBackground(adjustedPath, data, givenPath);
  55.         } else {
  56.             //创建节点
  57.             String path = protectedPathInForeground(adjustedPath, data, aclList);
  58.             returnPath = client.unfixForNamespace(path);
  59.         }
  60.         return returnPath;
  61.     }
  62.    
  63.     private String protectedPathInForeground(String adjustedPath, byte[] data, List aclList) throws Exception {
  64.         return pathInForeground(adjustedPath, data, aclList);
  65.     }
  66.    
  67.     private String pathInForeground(final String path, final byte[] data, final List aclList) throws Exception {
  68.         OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-Foreground");
  69.         final AtomicBoolean firstTime = new AtomicBoolean(true);
  70.         //重试调用
  71.         String returnPath = RetryLoop.callWithRetry(
  72.             client.getZookeeperClient(),
  73.             new Callable<String>() {
  74.                 @Override
  75.                 public String call() throws Exception {
  76.                     boolean localFirstTime = firstTime.getAndSet(false) && !debugForceFindProtectedNode;
  77.                     protectedMode.checkSetSessionId(client, createMode);
  78.                     String createdPath = null;
  79.                     if (!localFirstTime && protectedMode.doProtected()) {
  80.                         debugForceFindProtectedNode = false;
  81.                         createdPath = findProtectedNodeInForeground(path);
  82.                     }
  83.                     if (createdPath == null) {
  84.                         //在创建znode节点的时候,首先会调用CuratorFramework.getZooKeeper()获取zk客户端实例
  85.                         //之后就是通过原生zk客户端的API去创建节点了
  86.                         try {
  87.                             if (client.isZk34CompatibilityMode()) {
  88.                                 createdPath = client.getZooKeeper().create(path, data, aclList, createMode);
  89.                             } else {
  90.                                 createdPath = client.getZooKeeper().create(path, data, aclList, createMode, storingStat, ttl);
  91.                             }
  92.                         } catch (KeeperException.NoNodeException e) {
  93.                             if (createParentsIfNeeded) {
  94.                                 //这就是级联创建节点的实现
  95.                                 ZKPaths.mkdirs(client.getZooKeeper(), path, false, acling.getACLProviderForParents(), createParentsAsContainers);
  96.                                 if (client.isZk34CompatibilityMode()) {
  97.                                     createdPath = client.getZooKeeper().create(path, data, acling.getAclList(path), createMode);
  98.                                 } else {
  99.                                     createdPath = client.getZooKeeper().create(path, data, acling.getAclList(path), createMode, storingStat, ttl);
  100.                                 }
  101.                             } else {
  102.                                 throw e;
  103.                             }
  104.                         } catch (KeeperException.NodeExistsException e) {
  105.                             if (setDataIfExists) {
  106.                                 Stat setStat = client.getZooKeeper().setData(path, data, setDataIfExistsVersion);
  107.                                 if (storingStat != null) {
  108.                                     DataTree.copyStat(setStat, storingStat);
  109.                                 }
  110.                                 createdPath = path;
  111.                             } else {
  112.                                 throw e;
  113.                             }
  114.                         }
  115.                     }
  116.                     if (failNextCreateForTesting) {
  117.                         failNextCreateForTesting = false;
  118.                         throw new KeeperException.ConnectionLossException();
  119.                     }
  120.                     return createdPath;
  121.                 }
  122.             }
  123.         );
  124.         trace.setRequestBytesLength(data).setPath(path).commit();
  125.         return returnPath;
  126.     }
  127.     ...
  128. }
  129. public class CuratorFrameworkImpl implements CuratorFramework {
  130.     private final CuratorZookeeperClient client;
  131.     public CuratorFrameworkImpl(CuratorFrameworkFactory.Builder builder) {
  132.         ZookeeperFactory localZookeeperFactory = makeZookeeperFactory(builder.getZookeeperFactory());
  133.         this.client = new CuratorZookeeperClient(
  134.             localZookeeperFactory,
  135.             builder.getEnsembleProvider(),
  136.             builder.getSessionTimeoutMs(),
  137.             builder.getConnectionTimeoutMs(),
  138.             builder.getWaitForShutdownTimeoutMs(),
  139.             new Watcher() {
  140.                 ...
  141.             },
  142.             builder.getRetryPolicy(),
  143.             builder.canBeReadOnly(),
  144.             builder.getConnectionHandlingPolicy()
  145.         );
  146.         ...
  147.     }
  148.     ...
  149.     ZooKeeper getZooKeeper() throws Exception {
  150.         return client.getZooKeeper();
  151.     }
  152.     ...
  153. }
  154. public class CuratorZookeeperClient implements Closeable {
  155.     private final ConnectionState state;
  156.     ...
  157.     public ZooKeeper getZooKeeper() throws Exception {
  158.         Preconditions.checkState(started.get(), "Client is not started");
  159.         return state.getZooKeeper();
  160.     }
  161.     ...
  162. }
  163. class ConnectionState implements Watcher, Closeable {
  164.     private final HandleHolder zooKeeper;
  165.     ...
  166.     ZooKeeper getZooKeeper() throws Exception {
  167.         if (SessionFailRetryLoop.sessionForThreadHasFailed()) {
  168.             throw new SessionFailRetryLoop.SessionFailedException();
  169.         }
  170.         Exception exception = backgroundExceptions.poll();
  171.         if (exception != null) {
  172.             new EventTrace("background-exceptions", tracer.get()).commit();
  173.             throw exception;
  174.         }
  175.         boolean localIsConnected = isConnected.get();
  176.         if (!localIsConnected) {
  177.             checkTimeouts();
  178.         }
  179.         //通过HandleHolder获取ZooKeeper实例
  180.         return zooKeeper.getZooKeeper();
  181.     }
  182.     ...
  183. }
复制代码
(2)基于Curator查询znode节点
查询节点也使用了构造器模式:首先通过CuratorFramework的getData()方法创建一个GetDataBuilder实例,然后通过GetDataBuilder的forPath()方法 + 重试调用来查询znode节点。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端");
  12.         //查询节点
  13.         byte[] dataBytes = client.getData().forPath("/my/path");
  14.         System.out.println(new String(dataBytes));
  15.         //查询子节点
  16.         List<String> children = client.getChildren().forPath("/my");
  17.         System.out.println(children);
  18.     }
  19. }
  20. public class CuratorFrameworkImpl implements CuratorFramework {
  21.     ...
  22.     @Override
  23.     public GetDataBuilder getData() {
  24.         checkState();
  25.         return new GetDataBuilderImpl(this);
  26.     }
  27.    
  28.     @Override
  29.     public GetChildrenBuilder getChildren() {
  30.         checkState();
  31.         return new GetChildrenBuilderImpl(this);
  32.     }
  33.     ...
  34. }
  35. public class GetDataBuilderImpl implements GetDataBuilder, BackgroundOperation<String>, ErrorListenerPathable<byte[]> {
  36.     private final CuratorFrameworkImpl  client;
  37.     ...
  38.     @Override
  39.     public byte[] forPath(String path) throws Exception {
  40.         client.getSchemaSet().getSchema(path).validateWatch(path, watching.isWatched() || watching.hasWatcher());
  41.         path = client.fixForNamespace(path);
  42.         byte[] responseData = null;
  43.         if (backgrounding.inBackground()) {
  44.             client.processBackgroundOperation(new OperationAndData<String>(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching), null);
  45.         } else {
  46.             //查询节点
  47.             responseData = pathInForeground(path);
  48.         }
  49.         return responseData;
  50.     }
  51.    
  52.     private byte[] pathInForeground(final String path) throws Exception {
  53.         OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetDataBuilderImpl-Foreground");
  54.         //重试调用
  55.         byte[] responseData = RetryLoop.callWithRetry(
  56.             client.getZookeeperClient(),
  57.             new Callable<byte[]>() {
  58.                 @Override
  59.                 public byte[] call() throws Exception {
  60.                     byte[] responseData;
  61.                     //通过CuratorFramework获取原生zk客户端实例,然后调用其getData()获取节点
  62.                     if (watching.isWatched()) {
  63.                         responseData = client.getZooKeeper().getData(path, true, responseStat);
  64.                     } else {
  65.                         responseData = client.getZooKeeper().getData(path, watching.getWatcher(path), responseStat);
  66.                         watching.commitWatcher(KeeperException.NoNodeException.Code.OK.intValue(), false);
  67.                     }
  68.                     return responseData;
  69.                 }
  70.             }
  71.         );
  72.         trace.setResponseBytesLength(responseData).setPath(path).setWithWatcher(watching.hasWatcher()).setStat(responseStat).commit();
  73.         return decompress ? client.getCompressionProvider().decompress(path, responseData) : responseData;
  74.     }
  75.     ...
  76. }
复制代码
(3)基于Curator修改znode节点
修改节点也使用了构造器模式:首先通过CuratorFramework的setData()方法创建一个SetDataBuilder实例,然后通过SetDataBuilder的forPath()方法 + 重试调用来修改znode节点。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端");
  12.         //修改节点
  13.         client.setData().forPath("/my/path", "110".getBytes());
  14.         byte[] dataBytes = client.getData().forPath("/my/path");
  15.         System.out.println(new String(dataBytes));
  16.     }
  17. }
  18. public class CuratorFrameworkImpl implements CuratorFramework {
  19.     ...
  20.     @Override
  21.     public SetDataBuilder setData() {
  22.         checkState();
  23.         return new SetDataBuilderImpl(this);
  24.     }
  25.     ...
  26. }
  27. public class SetDataBuilderImpl implements SetDataBuilder, BackgroundOperation<PathAndBytes>, ErrorListenerPathAndBytesable<Stat> {
  28.     private final CuratorFrameworkImpl client;
  29.     ...
  30.     @Override
  31.     public Stat forPath(String path, byte[] data) throws Exception {
  32.         client.getSchemaSet().getSchema(path).validateGeneral(path, data, null);
  33.         if (compress) {
  34.             data = client.getCompressionProvider().compress(path, data);
  35.         }
  36.         path = client.fixForNamespace(path);
  37.         Stat resultStat = null;
  38.         if (backgrounding.inBackground()) {
  39.             client.processBackgroundOperation(new OperationAndData<>(this, new PathAndBytes(path, data), backgrounding.getCallback(), null, backgrounding.getContext(), null), null);
  40.         } else {
  41.             //修改节点
  42.             resultStat = pathInForeground(path, data);
  43.         }
  44.         return resultStat;
  45.     }
  46.    
  47.     private Stat pathInForeground(final String path, final byte[] data) throws Exception {
  48.         OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SetDataBuilderImpl-Foreground");
  49.         //重试调用
  50.         Stat resultStat = RetryLoop.callWithRetry(
  51.             client.getZookeeperClient(),
  52.             new Callable<Stat>() {
  53.                 @Override
  54.                 public Stat call() throws Exception {
  55.                     //通过CuratorFramework获取原生zk客户端实例,然后调用其setData()修改节点
  56.                     return client.getZooKeeper().setData(path, data, version);
  57.                 }
  58.             }
  59.         );
  60.         trace.setRequestBytesLength(data).setPath(path).setStat(resultStat).commit();
  61.         return resultStat;
  62.     }
  63.     ...
  64. }
复制代码
(4)基于Curator删除znode节点
删除节点也使用了构造器模式:首先通过CuratorFramework的delete()方法创建一个DeleteBuilder实例,然后通过DeleteBuilder的forPath()方法 + 重试调用来删除znode节点。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端");
  12.         //删除节点
  13.         client.delete().forPath("/my/path");
  14.     }
  15. }
  16. public class CuratorFrameworkImpl implements CuratorFramework {
  17.     ...
  18.     @Override
  19.     public DeleteBuilder delete() {
  20.         checkState();
  21.         return new DeleteBuilderImpl(this);
  22.     }
  23.     ...
  24. }
  25. public class DeleteBuilderImpl implements DeleteBuilder, BackgroundOperation<String>, ErrorListenerPathable<Void> {
  26.     private final CuratorFrameworkImpl client;
  27.     ...
  28.     @Override
  29.     public Void forPath(String path) throws Exception {
  30.         client.getSchemaSet().getSchema(path).validateDelete(path);
  31.         final String unfixedPath = path;
  32.         path = client.fixForNamespace(path);
  33.         if (backgrounding.inBackground()) {
  34.             OperationAndData.ErrorCallback<String> errorCallback = null;
  35.             if (guaranteed) {
  36.                 errorCallback = new OperationAndData.ErrorCallback<String>() {
  37.                     @Override
  38.                     public void retriesExhausted(OperationAndData<String> operationAndData) {
  39.                         client.getFailedDeleteManager().addFailedOperation(unfixedPath);
  40.                     }
  41.                 };
  42.             }
  43.             client.processBackgroundOperation(new OperationAndData<String>(this, path, backgrounding.getCallback(), errorCallback, backgrounding.getContext(), null), null);
  44.         } else {
  45.             //删除节点
  46.             pathInForeground(path, unfixedPath);
  47.         }
  48.         return null;
  49.     }
  50.     private void pathInForeground(final String path, String unfixedPath) throws Exception {
  51.         OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("DeleteBuilderImpl-Foreground");
  52.         //重试调用
  53.         RetryLoop.callWithRetry(
  54.             client.getZookeeperClient(),
  55.             new Callable<Void>() {
  56.                 @Override
  57.                 public Void call() throws Exception {
  58.                     try {
  59.                         //通过CuratorFramework获取原生zk客户端实例,然后调用其delete()删除节点
  60.                         client.getZooKeeper().delete(path, version);
  61.                     } catch (KeeperException.NoNodeException e) {
  62.                         if (!quietly) {
  63.                             throw e;
  64.                         }
  65.                     } catch (KeeperException.NotEmptyException e) {
  66.                         if (deletingChildrenIfNeeded) {
  67.                             ZKPaths.deleteChildren(client.getZooKeeper(), path, true);
  68.                         } else {
  69.                             throw e;
  70.                         }
  71.                     }
  72.                     return null;
  73.                 }
  74.             }
  75.         );
  76.         trace.setPath(path).commit();
  77.     }
  78. }
复制代码
 
11.Curator节点监听回调机制的实现源码
(1)PathCache子节点监听机制的实现源码
(2)NodeCache节点监听机制的实现源码
(3)getChildren()方法对子节点注册监听器和后台异步回调说明
(4)PathCache实现自动重复注册监听器的效果
(5)NodeCache实现节点变化事件监听的效果
 
(1)PathCache子节点监听机制的实现源码
PathChildrenCache会调用原生zk客户端对象的getChildren()方法,并往该方法传入一个监听器childrenWatcher。当子节点发生事件,就会通知childrenWatcher这个原生的Watcher,然后该Watcher便会调用注册到PathChildrenCache的Listener。注意:在传入的监听器Watcher中会实现重复注册Watcher。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端");
  12.         //PathCache,监听/cluster下的子节点变化
  13.         PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/cluster", true);
  14.         pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
  15.             public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
  16.                 ...
  17.             }
  18.         });
  19.         pathChildrenCache.start();
  20.     }
  21. }
  22. public class PathChildrenCache implements Closeable {
  23.     private final WatcherRemoveCuratorFramework client;
  24.     private final String path;
  25.     private final boolean cacheData;
  26.     private final boolean dataIsCompressed;
  27.     private final CloseableExecutorService executorService;
  28.     private final ListenerContainer<PathChildrenCacheListener> listeners = new ListenerContainer<PathChildrenCacheListener>();
  29.     ...
  30.     //初始化
  31.     public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final CloseableExecutorService executorService) {
  32.         this.client = client.newWatcherRemoveCuratorFramework();
  33.         this.path = PathUtils.validatePath(path);
  34.         this.cacheData = cacheData;
  35.         this.dataIsCompressed = dataIsCompressed;
  36.         this.executorService = executorService;
  37.         ensureContainers = new EnsureContainers(client, path);
  38.     }
  39.    
  40.     //获取用来存放Listener的容器listeners
  41.     public ListenerContainer<PathChildrenCacheListener> getListenable() {
  42.         return listeners;
  43.     }
  44.    
  45.     //启动对子节点的监听
  46.     public void start() throws Exception {
  47.         start(StartMode.NORMAL);
  48.     }
  49.    
  50.     private volatile ConnectionStateListener connectionStateListener = new ConnectionStateListener() {
  51.         @Override
  52.         public void stateChanged(CuratorFramework client, ConnectionState newState) {
  53.             //处理连接状态的变化
  54.             handleStateChange(newState);
  55.         }
  56.     };
  57.    
  58.     public void start(StartMode mode) throws Exception {
  59.         ...
  60.         //对建立的zk连接添加Listener
  61.         client.getConnectionStateListenable().addListener(connectionStateListener);
  62.         ...
  63.         //把PathChildrenCache自己传入RefreshOperation中
  64.         //下面的代码其实就是调用PathChildrenCache的refresh()方法
  65.         offerOperation(new RefreshOperation(this, RefreshMode.STANDARD));
  66.         ...
  67.     }
  68.    
  69.     //提交一个任务到线程池进行处理
  70.     void offerOperation(final Operation operation) {
  71.         if (operationsQuantizer.add(operation)) {
  72.             submitToExecutor(
  73.                 new Runnable() {
  74.                     @Override
  75.                     public void run() {
  76.                         ...
  77.                         operationsQuantizer.remove(operation);
  78.                         //其实就是调用PathChildrenCache的refresh()方法
  79.                         operation.invoke();
  80.                         ...
  81.                     }
  82.                 }
  83.             );
  84.         }
  85.     }
  86.    
  87.     private synchronized void submitToExecutor(final Runnable command) {
  88.         if (state.get() == State.STARTED) {
  89.             //提交一个任务到线程池进行处理
  90.             executorService.submit(command);
  91.         }
  92.     }
  93.     ...
  94. }
  95. class RefreshOperation implements Operation {
  96.     private final PathChildrenCache cache;
  97.     private final PathChildrenCache.RefreshMode mode;
  98.    
  99.     RefreshOperation(PathChildrenCache cache, PathChildrenCache.RefreshMode mode) {
  100.         this.cache = cache;
  101.         this.mode = mode;
  102.     }
  103.    
  104.     @Override
  105.     public void invoke() throws Exception {
  106.         //调用PathChildrenCache的refresh方法,也就是发起对子节点的监听
  107.         cache.refresh(mode);
  108.     }
  109.     ...
  110. }
  111. public class PathChildrenCache implements Closeable {
  112.     ...
  113.     private volatile Watcher childrenWatcher = new Watcher() {
  114.         //重复注册监听器
  115.         //当子节点发生变化事件时,该方法就会被触发调用
  116.         @Override
  117.         public void process(WatchedEvent event) {
  118.             //下面的代码其实依然是调用PathChildrenCache的refresh()方法
  119.             offerOperation(new RefreshOperation(PathChildrenCache.this, RefreshMode.STANDARD));
  120.         }
  121.     };
  122.    
  123.     void refresh(final RefreshMode mode) throws Exception {
  124.         ensurePath();
  125.         //创建一个回调,在下面执行client.getChildren()成功时会触发执行该回调
  126.         final BackgroundCallback callback = new BackgroundCallback() {
  127.             @Override
  128.             public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  129.                 if (reRemoveWatchersOnBackgroundClosed()) {
  130.                     return;
  131.                 }
  132.                 if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
  133.                     //处理子节点数据
  134.                     processChildren(event.getChildren(), mode);
  135.                 } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
  136.                     if (mode == RefreshMode.NO_NODE_EXCEPTION) {
  137.                         log.debug("KeeperException.NoNodeException received for getChildren() and refresh has failed. Resetting ensureContainers but not refreshing. Path: [{}]", path);
  138.                         ensureContainers.reset();
  139.                     } else {
  140.                         log.debug("KeeperException.NoNodeException received for getChildren(). Resetting ensureContainers. Path: [{}]", path);
  141.                         ensureContainers.reset();
  142.                         offerOperation(new RefreshOperation(PathChildrenCache.this, RefreshMode.NO_NODE_EXCEPTION));
  143.                     }
  144.                 }
  145.             }
  146.         };
  147.         //下面的代码最后会调用到原生zk客户端的getChildren方法发起对子节点的监听
  148.         //并且添加一个叫childrenWatcher的监听,一个叫callback的后台异步回调
  149.         client.getChildren().usingWatcher(childrenWatcher).inBackground(callback).forPath(path);
  150.     }
  151.     ...
  152. }
  153. //子节点发生变化事件时,最后都会触发执行EventOperation的invoke()方法
  154. class EventOperation implements Operation {
  155.     private final PathChildrenCache cache;
  156.     private final PathChildrenCacheEvent event;
  157.    
  158.     EventOperation(PathChildrenCache cache, PathChildrenCacheEvent event) {
  159.         this.cache = cache;
  160.         this.event = event;
  161.     }
  162.    
  163.     @Override
  164.     public void invoke() {
  165.         //调用PathChildrenCache的Listener
  166.         cache.callListeners(event);
  167.     }
  168.     ...
  169. }
复制代码
(2)NodeCache节点监听机制的实现源码
NodeCache会调用原生zk客户端对象的exists()方法,并往该方法传入一个监听器watcher。当子节点发生事件,就会通知watcher这个原生的Watcher,然后该Watcher便会调用注册到NodeCache的Listener。注意:在传入的监听器Watcher中会实现重复注册Watcher。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端");
  12.         //NodeCache
  13.         final NodeCache nodeCache = new NodeCache(client, "/cluster");
  14.         nodeCache.getListenable().addListener(new NodeCacheListener() {
  15.             public void nodeChanged() throws Exception {
  16.                 Stat stat = client.checkExists().forPath("/cluster");
  17.                 if (stat == null) {
  18.                 } else {
  19.                     nodeCache.getCurrentData();
  20.                 }
  21.             }
  22.         });
  23.         nodeCache.start();
  24.     }
  25. }
  26. public class NodeCache implements Closeable {
  27.     private final WatcherRemoveCuratorFramework client;
  28.     private final String path;
  29.     private final ListenerContainer<NodeCacheListener> listeners = new ListenerContainer<NodeCacheListener>();
  30.     ...
  31.     private ConnectionStateListener connectionStateListener = new ConnectionStateListener() {
  32.         @Override
  33.         public void stateChanged(CuratorFramework client, ConnectionState newState) {
  34.             if ((newState == ConnectionState.CONNECTED) || (newState == ConnectionState.RECONNECTED)) {
  35.                 if (isConnected.compareAndSet(false, true)) {
  36.                     reset();
  37.                 }
  38.             } else {
  39.                 isConnected.set(false);
  40.             }
  41.         }
  42.     };
  43.    
  44.     //初始化一个Watcher,作为监听器添加到下面reset()方法执行的client.checkExists()方法中
  45.     private Watcher watcher = new Watcher() {
  46.         //重复注册监听器
  47.         @Override
  48.         public void process(WatchedEvent event) {
  49.             reset();
  50.         }
  51.     };
  52.    
  53.     //初始化一个回调,在下面reset()方法执行client.checkExists()成功时会触发执行该回调
  54.     private final BackgroundCallback backgroundCallback = new BackgroundCallback() {
  55.         @Override
  56.         public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  57.             processBackgroundResult(event);
  58.         }
  59.     };
  60.    
  61.     //初始化NodeCache
  62.     public NodeCache(CuratorFramework client, String path, boolean dataIsCompressed) {
  63.         this.client = client.newWatcherRemoveCuratorFramework();
  64.         this.path = PathUtils.validatePath(path);
  65.         this.dataIsCompressed = dataIsCompressed;
  66.     }
  67.    
  68.     //获取存放Listener的容器ListenerContainer
  69.     public ListenerContainer<NodeCacheListener> getListenable() {
  70.         Preconditions.checkState(state.get() != State.CLOSED, "Closed");
  71.         return listeners;
  72.     }
  73.    
  74.     //启动对节点的监听
  75.     public void start() throws Exception {
  76.         start(false);
  77.     }
  78.    
  79.     public void start(boolean buildInitial) throws Exception {
  80.         Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");
  81.         //对建立的zk连接添加Listener
  82.         client.getConnectionStateListenable().addListener(connectionStateListener);
  83.         if (buildInitial) {
  84.             //调用原生的zk客户端的exists()方法,对节点进行监听
  85.             client.checkExists().creatingParentContainersIfNeeded().forPath(path);
  86.             internalRebuild();
  87.         }
  88.         reset();
  89.     }
  90.    
  91.     private void reset() throws Exception {
  92.         if ((state.get() == State.STARTED) && isConnected.get()) {
  93.             //下面的代码最后会调用原生的zk客户端的exists()方法,对节点进行监听
  94.             //并且添加一个叫watcher的监听,一个叫backgroundCallback的后台异步回调
  95.             client.checkExists().creatingParentContainersIfNeeded().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path);
  96.         }
  97.     }
  98.    
  99.     private void processBackgroundResult(CuratorEvent event) throws Exception {
  100.         switch (event.getType()) {
  101.             case GET_DATA: {
  102.                 if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
  103.                     ChildData childData = new ChildData(path, event.getStat(), event.getData());
  104.                     setNewData(childData);
  105.                 }
  106.                 break;
  107.             }
  108.             case EXISTS: {
  109.                 if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
  110.                     setNewData(null);
  111.                 } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
  112.                     if (dataIsCompressed) {
  113.                         client.getData().decompressed().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path);
  114.                     } else {
  115.                         client.getData().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path);
  116.                     }
  117.                 }
  118.                 break;
  119.             }
  120.         }
  121.     }
  122.     ...
  123. }
复制代码
(3)getChildren()方法对子节点注册监听器和后台异步回调说明
getChildren()方法注册的Watcher只有一次性,其注册的回调是一个异步回调。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端,完成zk的连接");
  12.         client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/test", "10".getBytes());
  13.         System.out.println("创建节点'/test");
  14.         client.getChildren().usingWatcher(new CuratorWatcher() {
  15.             public void process(WatchedEvent event) throws Exception {
  16.                 //只要通知过一次zk节点的变化,这里就不会再被通知了
  17.                 //也就是第一次的通知才有效,这里被执行过一次后,就不会再被执行
  18.                 System.out.println("收到一个zk的通知: " + event);
  19.             }
  20.         }).inBackground(new BackgroundCallback() {
  21.             //后台回调通知,表示会让zk.getChildren()在后台异步执行
  22.             //后台异步执行client.getChildren()方法完毕,便会回调这个方法进行通知
  23.             public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  24.                 System.out.println("收到一个后台回调通知: " + event);
  25.             }
  26.         }).forPath("/test");
  27.     }
  28. }
复制代码
(4)PathCache实现自动重复注册监听器的效果
每当节点发生变化时,就会触发childEvent()方法的调用。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         final CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端,完成zk的连接");
  12.         final PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/test", true);
  13.         pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
  14.             //只要子节点发生变化,无论变化多少次,每次变化都会触发这里childEvent的调用
  15.             public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
  16.                 System.out.println("监听的子节点发生变化,收到了事件通知:" + pathChildrenCacheEvent);
  17.             }
  18.         });
  19.         pathChildrenCache.start();
  20.         System.out.println("完成子节点的监听和启动");
  21.     }
  22. }
复制代码
(5)NodeCache实现节点变化事件监听的效果
每当节点发生变化时,就会触发nodeChanged()方法的调用。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         final CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端,完成zk的连接");
  12.         final NodeCache nodeCache = new NodeCache(client, "/test/child/id");
  13.         nodeCache.getListenable().addListener(new NodeCacheListener() {
  14.             //只要节点发生变化,无论变化多少次,每次变化都会触发这里nodeChanged的调用
  15.             public void nodeChanged() throws Exception {
  16.                 Stat stat = client.checkExists().forPath("/test/child/id");
  17.                 if (stat != null) {
  18.                     byte[] dataBytes = client.getData().forPath("/test/child/id");
  19.                     System.out.println("节点数据发生了变化:" + new String(dataBytes));
  20.                 } else {
  21.                     System.out.println("节点被删除");
  22.                 }
  23.             }
  24.         });
  25.         nodeCache.start();
  26.     }
  27. }
复制代码
 
12.基于Curator的Leader选举机制的实现源码
(1)第一种Leader选举机制LeaderLatch的源码
(2)第二种Leader选举机制LeaderSelector的源码
 
利用Curator的CRUD+ 监听回调机制,就能满足大部分系统使用zk的场景了。需要注意的是:如果使用原生的zk去注册监听器来监听节点或者子节点,当节点或子节点发生了对应的事件,会通知客户端一次,但是下一次再有对应的事件就不会通知了。使用zk原生的API时,客户端需要每次收到事件通知后,重新注册监听器。然而Curator的PathCache + NodeCache,会自动重新注册监听器。
 
(1)第一种Leader选举机制LeaderLatch的源码
Curator客户端会通过创建临时顺序节点的方式来竞争成为Leader的,LeaderLatch这种Leader选举的实现方式与分布式锁的实现几乎一样。
 
每个Curator客户端创建完临时顺序节点后,就会对/leader/latch目录调用getChildren()方法来获取里面所有的子节点,调用getChildren()方法的结果会通过backgroundCallback回调进行通知,接着客户端便对获取到的子节点进行排序来判断自己是否是第一个子节点。
 
如果客户端发现自己是第一个子节点,那么就是Leader。如果客户端发现自己不是第一个子节点,就对上一个节点添加一个监听器。在添加监听器时,会使用getData()方法获取自己的上一个节点,getData()方法执行成功后会调用backgrondCallback回调。
 
当上一个节点对应的客户端释放了Leader角色,上一个节点就会消失,此时就会通知第二个节点对应的客户端,执行getData()方法添加的监听器。
 
所以如果getData()方法的监听器被触发了,即发现上一个节点不存在了,客户端会调用getChildren()方法重新获取子节点列表,判断是否是Leader。
 
注意:使用getData()代替exists(),可以避免不必要的Watcher造成的资源泄露。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         final CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
  11.             public void stateChanged(CuratorFramework client, ConnectionState newState) {
  12.                 switch (newState) {
  13.                     case LOST:
  14.                         //当Leader与zk断开时,需要暂停当前Leader的工作
  15.                 }
  16.             }
  17.         });
  18.         client.start();
  19.         System.out.println("已经启动Curator客户端,完成zk的连接");
  20.         LeaderLatch leaderLatch = new LeaderLatch(client, "/leader/latch");
  21.         leaderLatch.start();
  22.         leaderLatch.await();//阻塞等待直到当前客户端成为Leader
  23.         Boolean hasLeaderShip = leaderLatch.hasLeadership();
  24.         System.out.println("是否成为Leader: " + hasLeaderShip);
  25.     }
  26. }
  27. public class LeaderLatch implements Closeable {
  28.     private final WatcherRemoveCuratorFramework client;
  29.     private final ConnectionStateListener listener = new ConnectionStateListener() {
  30.         @Override
  31.         public void stateChanged(CuratorFramework client, ConnectionState newState) {
  32.             handleStateChange(newState);
  33.         }
  34.     };
  35.     ...
  36.     //Add this instance to the leadership election and attempt to acquire leadership.
  37.     public void start() throws Exception {
  38.         ...
  39.         //对建立的zk连接添加Listener
  40.         client.getConnectionStateListenable().addListener(listener);
  41.         reset();
  42.         ...
  43.     }
  44.    
  45.     @VisibleForTesting
  46.     void reset() throws Exception {
  47.         setLeadership(false);
  48.         setNode(null);
  49.         //callback作为成功创建临时顺序节点后的回调
  50.         BackgroundCallback callback = new BackgroundCallback() {
  51.             @Override
  52.             public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  53.                 ...
  54.                 if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
  55.                     setNode(event.getName());
  56.                     if (state.get() == State.CLOSED) {
  57.                         setNode(null);
  58.                     } else {
  59.                         //成功创建临时顺序节点,需要通过getChildren()再去获取子节点列表
  60.                         getChildren();
  61.                     }
  62.                 } else {
  63.                     log.error("getChildren() failed. rc = " + event.getResultCode());
  64.                 }
  65.             }
  66.         };
  67.         //创建临时顺序节点
  68.         client.create().creatingParentContainersIfNeeded().withProtection()
  69.             .withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback)
  70.             .forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id));
  71.     }
  72.    
  73.     //获取子节点列表
  74.     private void getChildren() throws Exception {
  75.         //callback作为成功获取子节点列表后的回调
  76.         BackgroundCallback callback = new BackgroundCallback() {
  77.             @Override
  78.             public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  79.                 if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
  80.                     checkLeadership(event.getChildren());
  81.                 }
  82.             }
  83.         };
  84.         client.getChildren().inBackground(callback).forPath(ZKPaths.makePath(latchPath, null));
  85.     }
  86.    
  87.     //检查自己是否是第一个节点
  88.     private void checkLeadership(List<String> children) throws Exception {
  89.         if (debugCheckLeaderShipLatch != null) {
  90.             debugCheckLeaderShipLatch.await();
  91.         }
  92.         final String localOurPath = ourPath.get();
  93.         //对获取到的节点进行排序
  94.         List<String> sortedChildren = LockInternals.getSortedChildren(LOCK_NAME, sorter, children);
  95.         int ourIndex = (localOurPath != null) ? sortedChildren.indexOf(ZKPaths.getNodeFromPath(localOurPath)) : -1;
  96.         if (ourIndex < 0) {
  97.             log.error("Can't find our node. Resetting. Index: " + ourIndex);
  98.             reset();
  99.         } else if (ourIndex == 0) {
  100.             //如果自己是第一个节点,则标记自己为Leader
  101.             setLeadership(true);
  102.         } else {
  103.             //如果自己不是第一个节点,则对前一个节点添加监听
  104.             String watchPath = sortedChildren.get(ourIndex - 1);
  105.             Watcher watcher = new Watcher() {
  106.                 @Override
  107.                 public void process(WatchedEvent event) {
  108.                     if ((state.get() == State.STARTED) && (event.getType() == Event.EventType.NodeDeleted) && (localOurPath != null)) {
  109.                         //重新获取子节点列表
  110.                         getChildren();
  111.                     }
  112.                 }
  113.             };
  114.             BackgroundCallback callback = new BackgroundCallback() {
  115.                 @Override
  116.                 public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  117.                     if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
  118.                         reset();
  119.                     }
  120.                 }
  121.             };
  122.             //use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak
  123.             //使用getData()代替exists(),可以避免不必要的Watcher造成的资源泄露
  124.             client.getData().usingWatcher(watcher).inBackground(callback).forPath(ZKPaths.makePath(latchPath, watchPath));
  125.         }
  126.     }
  127.     ...
  128.     //阻塞等待直到成为Leader
  129.     public void await() throws InterruptedException, EOFException {
  130.         synchronized(this) {
  131.             while ((state.get() == State.STARTED) && !hasLeadership.get()) {
  132.                 wait();//Objetc对象的wait()方法,阻塞等待
  133.             }
  134.         }
  135.         if (state.get() != State.STARTED) {
  136.             throw new EOFException();
  137.         }
  138.     }
  139.    
  140.     //设置当前客户端成为Leader,并进行notifyAll()通知之前阻塞的线程
  141.     private synchronized void setLeadership(boolean newValue) {
  142.         boolean oldValue = hasLeadership.getAndSet(newValue);
  143.         if (oldValue && !newValue) { // Lost leadership, was true, now false
  144.             listeners.forEach(new Function<LeaderLatchListener, Void>() {
  145.                 @Override
  146.                 public Void apply(LeaderLatchListener listener) {
  147.                     listener.notLeader();
  148.                     return null;
  149.                 }
  150.             });
  151.         } else if (!oldValue && newValue) { // Gained leadership, was false, now true
  152.             listeners.forEach(new Function<LeaderLatchListener, Void>() {
  153.                 @Override
  154.                 public Void apply(LeaderLatchListener input) {
  155.                     input.isLeader();
  156.                     return null;
  157.                 }
  158.             });
  159.         }
  160.         notifyAll();//唤醒之前执行了wait()方法的线程
  161.     }
  162. }
复制代码
(2)第二种Leader选举机制LeaderSelector的源码
通过判断是否成功获取到分布式锁,来判断是否竞争成为Leader。正因为是通过持有分布式锁来成为Leader,所以LeaderSelector.takeLeadership()方法不能退出,否则就会释放锁。而一旦释放了锁,其他客户端就会竞争锁成功而成为新的Leader。
  1. public class Demo {
  2.     public static void main(String[] args) throws Exception {
  3.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  4.         final CuratorFramework client = CuratorFrameworkFactory.newClient(
  5.             "127.0.0.1:2181",//zk的地址
  6.             5000,//客户端和zk的心跳超时时间,超过该时间没心跳,Session就会被断开
  7.             3000,//连接zk时的超时时间
  8.             retryPolicy
  9.         );
  10.         client.start();
  11.         System.out.println("已经启动Curator客户端,完成zk的连接");
  12.         LeaderSelector leaderSelector = new LeaderSelector(
  13.             client,
  14.             "/leader/election",
  15.             new LeaderSelectorListener() {
  16.                 public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
  17.                     System.out.println("你已经成为了Leader......");
  18.                     //在这里干Leader所有的事情,此时方法不能退出
  19.                     Thread.sleep(Integer.MAX_VALUE);
  20.                 }
  21.                 public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
  22.                     System.out.println("连接状态的变化,已经不是Leader......");
  23.                     if (connectionState.equals(ConnectionState.LOST)) {
  24.                         throw new CancelLeadershipException();
  25.                     }
  26.                 }
  27.             }
  28.         );
  29.         leaderSelector.start();//尝试和其他节点在节点"/leader/election"上进行竞争成为Leader
  30.         Thread.sleep(Integer.MAX_VALUE);
  31.     }
  32. }
  33. public class LeaderSelector implements Closeable {
  34.     private final CuratorFramework client;
  35.     private final LeaderSelectorListener listener;
  36.     private final CloseableExecutorService executorService;
  37.     private final InterProcessMutex mutex;
  38.     ...
  39.     public LeaderSelector(CuratorFramework client, String leaderPath, CloseableExecutorService executorService, LeaderSelectorListener listener) {
  40.         Preconditions.checkNotNull(client, "client cannot be null");
  41.         PathUtils.validatePath(leaderPath);
  42.         Preconditions.checkNotNull(listener, "listener cannot be null");
  43.         this.client = client;
  44.         this.listener = new WrappedListener(this, listener);
  45.         hasLeadership = false;
  46.         this.executorService = executorService;
  47.         //初始化一个分布式锁
  48.         mutex = new InterProcessMutex(client, leaderPath) {
  49.             @Override
  50.             protected byte[] getLockNodeBytes() {
  51.                 return (id.length() > 0) ? getIdBytes(id) : null;
  52.             }
  53.         };
  54.     }
  55.    
  56.     public void start() {
  57.         Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");
  58.         Preconditions.checkState(!executorService.isShutdown(), "Already started");
  59.         Preconditions.checkState(!hasLeadership, "Already has leadership");
  60.         client.getConnectionStateListenable().addListener(listener);
  61.         requeue();
  62.     }
  63.    
  64.     public boolean requeue() {
  65.         Preconditions.checkState(state.get() == State.STARTED, "close() has already been called");
  66.         return internalRequeue();
  67.     }
  68.    
  69.     private synchronized boolean internalRequeue() {
  70.         if (!isQueued && (state.get() == State.STARTED)) {
  71.             isQueued = true;
  72.             //将选举的工作作为一个任务交给线程池执行
  73.             Future<Void> task = executorService.submit(new Callable<Void>() {
  74.                 @Override
  75.                 public Void call() throws Exception {
  76.                     ...
  77.                     doWorkLoop();
  78.                     ...
  79.                     return null;
  80.                 }
  81.             });
  82.             ourTask.set(task);
  83.             return true;
  84.         }
  85.         return false;
  86.     }
  87.    
  88.     private void doWorkLoop() throws Exception {
  89.         ...
  90.         doWork();
  91.         ...
  92.     }
  93.    
  94.     @VisibleForTesting
  95.     void doWork() throws Exception {
  96.         hasLeadership = false;
  97.         try {
  98.             //尝试获取一把分布式锁,获取失败会进行阻塞
  99.             mutex.acquire();
  100.             //执行到这一行代码,说明获取分布式锁成功
  101.             hasLeadership = true;
  102.             try {
  103.                 if (debugLeadershipLatch != null) {
  104.                     debugLeadershipLatch.countDown();
  105.                 }
  106.                 if (debugLeadershipWaitLatch != null) {
  107.                     debugLeadershipWaitLatch.await();
  108.                 }
  109.                 //回调用户重写的takeLeadership()方法
  110.                 listener.takeLeadership(client);
  111.             } catch (InterruptedException e) {
  112.                 Thread.currentThread().interrupt();
  113.                 throw e;
  114.             } catch (Throwable e) {
  115.                 ThreadUtils.checkInterrupted(e);
  116.             } finally {
  117.                 clearIsQueued();
  118.             }
  119.         } catch (InterruptedException e) {
  120.             Thread.currentThread().interrupt();
  121.             throw e;
  122.         } finally {
  123.             if (hasLeadership) {
  124.                 hasLeadership = false;
  125.                 boolean wasInterrupted = Thread.interrupted();  // clear any interrupted tatus so that mutex.release() works immediately
  126.                 try {
  127.                     //释放锁
  128.                     mutex.release();
  129.                 } catch (Exception e) {
  130.                     if (failedMutexReleaseCount != null) {
  131.                         failedMutexReleaseCount.incrementAndGet();
  132.                     }
  133.                     ThreadUtils.checkInterrupted(e);
  134.                     log.error("The leader threw an exception", e);
  135.                 } finally {
  136.                     if (wasInterrupted) {
  137.                         Thread.currentThread().interrupt();
  138.                     }
  139.                 }
  140.             }
  141.         }
  142.     }
  143.     ...
  144. }
复制代码
 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册