Java Code Examples for org.apache.curator.framework.recipes.cache.PathChildrenCache

The following examples show how to use org.apache.curator.framework.recipes.cache.PathChildrenCache. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: curator-extensions   Source File: NodeDiscovery.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of {@code ZooKeeperNodeDiscovery}.
 *
 * @param curator    Curator framework reference.
 * @param nodePath   The path in ZooKeeper to watch.
 * @param parser     The strategy to convert from ZooKeeper {@code byte[]} to {@code T}.
 */
public NodeDiscovery(CuratorFramework curator, String nodePath, NodeDataParser<T> parser) {
    Objects.requireNonNull(curator);
    Objects.requireNonNull(nodePath);
    Objects.requireNonNull(parser);
    checkArgument(curator.getState() == CuratorFrameworkState.STARTED);
    checkArgument(!"".equals(nodePath));

    ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat(getClass().getSimpleName() + "(" + nodePath + ")-%d")
            .setDaemon(true)
            .build();

    _nodes = new ConcurrentHashMap<>();
    _listeners = Collections.newSetFromMap(new ConcurrentHashMap<>());
    _curator = curator;
    _executor = Executors.newSingleThreadScheduledExecutor(threadFactory);
    _pathCache = new PathChildrenCache(curator, nodePath, true, false, _executor);
    _nodeDataParser = parser;
    _closed = false;
}
 
Example 2
Source Project: sofa-dashboard   Source File: ZookeeperAdminRegistry.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(String group, RegistryDataChangeListener listener) {
    // 注册Consumer节点
    try {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient,
            SofaDashboardConstants.SEPARATOR + group, true);

        pathChildrenCache.start(PathChildrenCache.StartMode.NORMAL);

        pathChildrenCache.getListenable().addListener(rootNodeChangeListener);
    } catch (Exception e) {
        throw new SofaRpcRuntimeException("Failed to register consumer to zookeeperRegistry!",
            e);
    }

}
 
Example 3
Source Project: workflow   Source File: Scheduler.java    License: Apache License 2.0 6 votes vote down vote up
private boolean taskIsComplete(PathChildrenCache completedTasksCache, RunId runId, ExecutableTask task)
{
    if ( (task == null) || !task.isExecutable() )
    {
        return true;
    }
    String completedTaskPath = ZooKeeperConstants.getCompletedTaskPath(runId, task.getTaskId());
    ChildData currentData = completedTasksCache.getCurrentData(completedTaskPath);
    if ( currentData != null )
    {
        TaskExecutionResult result = workflowManager.getSerializer().deserialize(currentData.getData(), TaskExecutionResult.class);
        if ( result.getSubTaskRunId().isPresent() )
        {
            RunnableTask runnableTask = getRunnableTask(result.getSubTaskRunId().get());
            return (runnableTask != null) && runnableTask.getCompletionTimeUtc().isPresent();
        }
        return true;
    }
    return false;
}
 
Example 4
Source Project: turbo-rpc   Source File: ZooKeeperDiscover.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException {
	for (int i = 0; i < watchers.size(); i++) {
		PathChildrenCache watcher = watchers.get(i);

		try {
			watcher.close();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("watcher关闭失败 ", e);
			}
		}
	}

	watchers = null;

	client.close();
	client = null;
}
 
Example 5
/**
 * fetch the Path cache when the task sync
 */
protected PathChildrenCache getPathCache(TaskDO taskDO) {
    return pathChildrenCacheMap.computeIfAbsent(taskDO.getTaskId(), (key) -> {
        try {
            PathChildrenCache pathChildrenCache =
                new PathChildrenCache(zookeeperServerHolder.get(taskDO.getSourceClusterId(), ""),
                    convertDubboProvidersPath(taskDO.getServiceName()), false);
            pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
            return pathChildrenCache;
        } catch (Exception e) {
            log.error("zookeeper path children cache start failed, taskId:{}", taskDO.getTaskId(), e);
            return null;
        }
    });

}
 
Example 6
Source Project: fluo   Source File: TransactorCache.java    License: Apache License 2.0 6 votes vote down vote up
public TransactorCache(Environment env) {
  final FluoConfiguration conf = env.getConfiguration();

  timeoutCache =
      CacheBuilder.newBuilder().maximumSize(FluoConfigurationImpl.getTransactorMaxCacheSize(conf))
          .expireAfterAccess(
              FluoConfigurationImpl.getTransactorCacheTimeout(conf, TimeUnit.MILLISECONDS),
              TimeUnit.MILLISECONDS)
          .concurrencyLevel(10).build();

  this.env = env;
  cache = new PathChildrenCache(env.getSharedResources().getCurator(),
      ZookeeperPath.TRANSACTOR_NODES, true);
  try {
    cache.start(StartMode.BUILD_INITIAL_CACHE);
    status = TcStatus.OPEN;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
Source Project: hermes   Source File: MetaServerAssignmentHolder.java    License: Apache License 2.0 6 votes vote down vote up
private void initPathChildrenCache() throws InitializationException {
	m_pathChildrenCache = new PathChildrenCache(m_zkClient.get(), ZKPathUtils.getMetaServerAssignmentRootZkPath(),
	      true);

	m_pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

		@Override
		public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
			if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED
			      || event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED
			      || event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
				String topic = ZKPathUtils.lastSegment(event.getData().getPath());
				m_topiAssignmentCache.invalidate(topic);
			}
		}
	});

	try {
		m_pathChildrenCache.start(StartMode.BUILD_INITIAL_CACHE);
	} catch (Exception e) {
		throw new InitializationException("Init metaServerAssignmentHolder failed.", e);
	}
}
 
Example 8
@Provides
@Singleton
@Exposed
ServiceGroupMonitor provideServiceGroupMonitor(
    ShutdownRegistry shutdownRegistry,
    CuratorFramework client) {

  PathChildrenCache groupCache =
      new PathChildrenCache(client, discoveryPath, true /* cacheData */);

  // NB: Even though we do not start the serviceGroupMonitor here, the registered close shutdown
  // action is safe since the underlying PathChildrenCache close is tolerant of an un-started
  // state. Its also crucial so that its underlying groupCache is closed prior to its
  // curatorFramework dependency in the case when the PathChildrenCache is in fact started (via
  // CuratorServiceGroupMonitor::start) since a CuratorFramework should have no active clients
  // when it is closed to avoid errors in those clients when attempting to use it.

  ServiceGroupMonitor serviceGroupMonitor =
      new CuratorServiceGroupMonitor(groupCache, MEMBER_SELECTOR);
  shutdownRegistry.addAction(groupCache::close);

  return serviceGroupMonitor;
}
 
Example 9
Source Project: jigsaw-payment   Source File: RefreshableTransportPool.java    License: Apache License 2.0 6 votes vote down vote up
public void start() throws Exception {
    if (this.cache == null) {
        if (this.executorService == null) {
            this.cache = new PathChildrenCache(client, path, cacheData);
        } else {
            this.cache = new PathChildrenCache(client, path, cacheData,
                    dataIsCompressed, this.executorService);
        }
    }
    this.cache.getListenable().addListener(this);
    this.cache.start(StartMode.POST_INITIALIZED_EVENT);
    //this.prepareInstances();
    // call super to initialize the pool;
    super.start();
    LOG.info("transport pooling factory started. ");
}
 
Example 10
Source Project: twister2   Source File: ZKBarrierHandler.java    License: Apache License 2.0 6 votes vote down vote up
private long getInitialWorkersAtBarrier(PathChildrenCache childrenCache,
                                        Set<Integer> workersAtBarrier) {

  long timeout = 0;
  List<ChildData> existingWorkerZnodes = childrenCache.getCurrentData();
  for (ChildData child: existingWorkerZnodes) {
    String fullPath = child.getPath();
    int workerID = ZKUtils.getWorkerIDFromPersPath(fullPath);
    workersAtBarrier.add(workerID);

    if (timeout == 0) {
      try {
        ZKBarrierManager.readWorkerTimeout(client, fullPath);
      } catch (Twister2Exception e) {
        throw new Twister2RuntimeException(e);
      }
    }
  }

  return timeout;
}
 
Example 11
Source Project: twister2   Source File: ZKMasterController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * create the listener for ephemeral worker znodes to determine worker joins and failures
 */
private void addEphemChildrenCacheListener(PathChildrenCache cache) {
  PathChildrenCacheListener listener = new PathChildrenCacheListener() {

    public void childEvent(CuratorFramework clientOfEvent, PathChildrenCacheEvent event) {

      switch (event.getType()) {
        case CHILD_ADDED:
          workerZnodeAdded(event);
          break;

        case CHILD_REMOVED:
          workerZnodeRemoved(event);
          break;

        default:
          // nothing to do
      }
    }
  };
  cache.getListenable().addListener(listener);
}
 
Example 12
Source Project: twister2   Source File: ZKMasterController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * create the listener for persistent worker znodes to determine worker status changes
 */
private void addPersChildrenCacheListener(PathChildrenCache cache) {
  PathChildrenCacheListener listener = new PathChildrenCacheListener() {

    public void childEvent(CuratorFramework clientOfEvent, PathChildrenCacheEvent event) {

      switch (event.getType()) {

        case CHILD_UPDATED:
          childZnodeUpdated(event);
          break;

        default:
          // nothing to do
      }
    }
  };
  cache.getListenable().addListener(listener);
}
 
Example 13
Source Project: twister2   Source File: ZKWorkerController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * listen for additions to the job events directory in zk server
 * @param cache
 */
private void addEventsChildrenCacheListener(PathChildrenCache cache) {
  PathChildrenCacheListener listener = new PathChildrenCacheListener() {

    public void childEvent(CuratorFramework clientOfEvent, PathChildrenCacheEvent event) {

      switch (event.getType()) {
        case CHILD_ADDED:
          eventPublished(event);
          break;

        default:
          // nothing to do
      }
    }
  };
  cache.getListenable().addListener(listener);
}
 
Example 14
Source Project: Mycat2   Source File: ZKUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void addChildPathCache(String path, PathChildrenCacheListener listener) {
    NameableExecutor businessExecutor = MycatServer.getInstance().getBusinessExecutor();
    ExecutorService executor = businessExecutor == null ? Executors.newFixedThreadPool(5) : businessExecutor;

    try {
        /**
         * 监听子节点的变化情况
         */
        final PathChildrenCache childrenCache = new PathChildrenCache(getConnection(), path, true);
        childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        childrenCache.getListenable().addListener(listener, executor);
        watchMap.put(path, childrenCache);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source Project: GoPush   Source File: ZkUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
     * 设置子节点更改监听
     *
     * @param path
     * @throws Exception
     */
    public boolean listenerPathChildrenCache(String path, BiConsumer<CuratorFramework, PathChildrenCacheEvent> biConsumer) {

        if (!ObjectUtils.allNotNull(zkClient, path, biConsumer)) {
            return Boolean.FALSE;
        }
        try {
            Stat stat = exists(path);
            if (stat != null) {
                PathChildrenCache watcher = new PathChildrenCache(zkClient, path, true);
                watcher.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
                //该模式下 watcher在重连的时候会自动 rebuild 否则需要重新rebuild
                watcher.getListenable().addListener(biConsumer::accept, pool);
                if (!pathChildrenCaches.contains(watcher)) {
                    pathChildrenCaches.add(watcher);
                }
//                else{
//                    watcher.rebuild();
//                }
                return Boolean.TRUE;
            }
        } catch (Exception e) {
            log.error("listen path children cache fail! path:{} , error:{}", path, e);
        }
        return Boolean.FALSE;
    }
 
Example 16
Source Project: niubi-job   Source File: MasterSlaveJobSummaryListener.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void listen() throws Exception {
    MasterSlaveApiFactory masterSlaveApiFactory = new MasterSlaveApiFactoryImpl(client);
    PathChildrenCache pathChildrenCache = new PathChildrenCache(client, masterSlaveApiFactory.pathApi().getJobPath(), true);
    pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
        @Override
        public synchronized void childEvent(CuratorFramework clientInner, PathChildrenCacheEvent event) throws Exception {
            if (!EventHelper.isChildUpdateEvent(event) && !EventHelper.isChildAddEvent(event)) {
                return;
            }
            MasterSlaveJobData masterSlaveJobData = new MasterSlaveJobData(event.getData());
            if (!masterSlaveJobData.getData().isOperated()) {
                return;
            }
            LoggerHelper.info("begin update master-slave job summary " + masterSlaveJobData.getData());
            masterSlaveJobSummaryService.updateJobSummary(masterSlaveJobData.getData());
            masterSlaveJobLogService.updateJobLog(masterSlaveJobData.getData());
            LoggerHelper.info("update master-slave job summary successfully " + masterSlaveJobData.getData());
        }
    });
    pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
}
 
Example 17
Source Project: emodb   Source File: PartitionedLeaderService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    if (_serviceFactory == null) {
        throw new IllegalStateException("Cannot start service without first providing a service factory");
    }
    
    String participantsPath = ZKPaths.makePath(_basePath, String.format(LEADER_PATH_PATTERN, 0));

    // Watch the participants for partition 0 to determine how many potential leaders there are total
    _participantsCache = new PathChildrenCache(_curator, participantsPath, true);
    _participantsCache.getListenable().addListener((ignore1, ignore2) -> participantsUpdated(false));
    _participantsCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
    participantsUpdated(true);
    
    List<Future<Void>> futures = Lists.newArrayListWithCapacity(_numPartitions);

    for (PartitionLeader partitionLeader : _partitionLeaders) {
        futures.add(partitionLeader.startAsync());
    }

    for (Future<Void> future : futures) {
        future.get();
    }
}
 
Example 18
/**
 * Submitted job graph store backed by ZooKeeper.
 *
 * @param zooKeeperFullBasePath ZooKeeper path for current job graphs
 * @param zooKeeperStateHandleStore State storage used to persist the submitted jobs
 */
public ZooKeeperSubmittedJobGraphStore(
		String zooKeeperFullBasePath,
		ZooKeeperStateHandleStore<SubmittedJobGraph> zooKeeperStateHandleStore,
		PathChildrenCache pathCache) {

	checkNotNull(zooKeeperFullBasePath, "Current jobs path");

	this.zooKeeperFullBasePath = zooKeeperFullBasePath;
	this.jobGraphsInZooKeeper = checkNotNull(zooKeeperStateHandleStore);

	this.pathCache = checkNotNull(pathCache);
	pathCache.getListenable().addListener(new SubmittedJobGraphsPathCacheListener());
}
 
Example 19
@Nonnull
private ZooKeeperSubmittedJobGraphStore createZooKeeperSubmittedJobGraphStore(String fullPath) throws Exception {
	final CuratorFramework client = ZooKeeper.getClient();
	// Ensure that the job graphs path exists
	client.newNamespaceAwareEnsurePath(fullPath).ensure(client.getZookeeperClient());

	// All operations will have the path as root
	CuratorFramework facade = client.usingNamespace(client.getNamespace() + fullPath);
	return new ZooKeeperSubmittedJobGraphStore(
		fullPath,
		new ZooKeeperStateHandleStore<>(
			facade,
			localStateStorage),
		new PathChildrenCache(facade, "/", false));
}
 
Example 20
Source Project: flink   Source File: ZooKeeperUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link ZooKeeperSubmittedJobGraphStore} instance.
 *
 * @param client        The {@link CuratorFramework} ZooKeeper client to use
 * @param configuration {@link Configuration} object
 * @return {@link ZooKeeperSubmittedJobGraphStore} instance
 * @throws Exception if the submitted job graph store cannot be created
 */
public static ZooKeeperSubmittedJobGraphStore createSubmittedJobGraphs(
		CuratorFramework client,
		Configuration configuration) throws Exception {

	checkNotNull(configuration, "Configuration");

	RetrievableStateStorageHelper<SubmittedJobGraph> stateStorage = createFileSystemStateStorage(configuration, "submittedJobGraph");

	// ZooKeeper submitted jobs root dir
	String zooKeeperSubmittedJobsPath = configuration.getString(HighAvailabilityOptions.HA_ZOOKEEPER_JOBGRAPHS_PATH);

	// Ensure that the job graphs path exists
	client.newNamespaceAwareEnsurePath(zooKeeperSubmittedJobsPath)
		.ensure(client.getZookeeperClient());

	// All operations will have the path as root
	CuratorFramework facade = client.usingNamespace(client.getNamespace() + zooKeeperSubmittedJobsPath);

	final String zooKeeperFullSubmittedJobsPath = client.getNamespace() + zooKeeperSubmittedJobsPath;

	final ZooKeeperStateHandleStore<SubmittedJobGraph> zooKeeperStateHandleStore = new ZooKeeperStateHandleStore<>(facade, stateStorage);

	final PathChildrenCache pathCache = new PathChildrenCache(facade, "/", false);

	return new ZooKeeperSubmittedJobGraphStore(
		zooKeeperFullSubmittedJobsPath,
		zooKeeperStateHandleStore,
		pathCache);
}
 
Example 21
Source Project: x-pipe   Source File: TestPathChildren.java    License: Apache License 2.0 5 votes vote down vote up
private void printAllData(PathChildrenCache pathChildrenCache) {

        logger.info("[begin]-------------");
        for (ChildData childData : pathChildrenCache.getCurrentData()) {
            logger.info("{}", childData.getPath());
        }
        logger.info("[end]-------------");
    }
 
Example 22
Source Project: flink   Source File: ZooKeeperSubmittedJobGraphStoreTest.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public ZooKeeperSubmittedJobGraphStore createSubmittedJobGraphStore(CuratorFramework client, TestingRetrievableStateStorageHelper<SubmittedJobGraph> stateStorage) throws Exception {
	return new ZooKeeperSubmittedJobGraphStore(
		client.getNamespace(),
		new ZooKeeperStateHandleStore<>(client, stateStorage),
		new PathChildrenCache(client, "/", false));
}
 
Example 23
@Nonnull
private ZooKeeperSubmittedJobGraphStore createZooKeeperSubmittedJobGraphStore(String fullPath) throws Exception {
	final CuratorFramework client = ZooKeeper.getClient();
	// Ensure that the job graphs path exists
	client.newNamespaceAwareEnsurePath(fullPath).ensure(client.getZookeeperClient());

	// All operations will have the path as root
	CuratorFramework facade = client.usingNamespace(client.getNamespace() + fullPath);
	return new ZooKeeperSubmittedJobGraphStore(
		fullPath,
		new ZooKeeperStateHandleStore<>(
			facade,
			localStateStorage),
		new PathChildrenCache(facade, "/", false));
}
 
Example 24
/**
 * 订阅接口级配置
 *
 * @param config   provider/consumer config
 * @param listener config listener
 */
protected void subscribeConfig(final AbstractInterfaceConfig config, ConfigListener listener) {
    try {
        if (configObserver == null) {
            configObserver = new ZookeeperConfigObserver();
        }
        configObserver.addConfigListener(config, listener);
        final String configPath = buildConfigPath(rootPath, config);
        // 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, configPath, true);
        pathChildrenCache.getListenable().addListener((client1, event) -> {
            if (LOGGER.isDebugEnabled(config.getAppName())) {
                LOGGER.debug("Receive zookeeper event: " + "type=[" + event.getType() + "]");
            }
            switch (event.getType()) {
                case CHILD_ADDED:
                    configObserver.addConfig(config, configPath, event.getData());
                    break;
                case CHILD_REMOVED:
                    configObserver.removeConfig(config, configPath, event.getData());
                    break;
                case CHILD_UPDATED:
                    configObserver.updateConfig(config, configPath, event.getData());
                    break;
                default:
                    break;
            }
        });
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        INTERFACE_CONFIG_CACHE.put(configPath, pathChildrenCache);
        configObserver.updateConfigAll(config, configPath, pathChildrenCache.getCurrentData());
    } catch (Throwable t) {
        throw new SofaRpcRuntimeException(
            "Failed to subscribe provider config from zookeeperRegistry!", t);
    }
}
 
Example 25
/**
 * 订阅IP级配置(服务发布暂时不支持动态配置,暂时支持订阅ConsumerConfig参数设置)
 *
 * @param config   consumer config
 * @param listener config listener
 */
protected void subscribeOverride(final ConsumerConfig config, ConfigListener listener) {
    try {
        if (overrideObserver == null) {
            overrideObserver = new ZookeeperOverrideObserver();
        }
        overrideObserver.addConfigListener(config, listener);
        final String overridePath = buildOverridePath(rootPath, config);
        final AbstractInterfaceConfig registerConfig = getRegisterConfig(config);
        // 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, overridePath,
            true);
        pathChildrenCache.getListenable().addListener((client1, event) -> {
            if (LOGGER.isDebugEnabled(config.getAppName())) {
                LOGGER.debug("Receive zookeeper event: " + "type=[" + event.getType() + "]");
            }
            switch (event.getType()) {
                case CHILD_ADDED:
                    overrideObserver.addConfig(config, overridePath, event.getData());
                    break;
                case CHILD_REMOVED:
                    overrideObserver.removeConfig(config, overridePath, event.getData(),
                        registerConfig);
                    break;
                case CHILD_UPDATED:
                    overrideObserver.updateConfig(config, overridePath, event.getData());
                    break;
                default:
                    break;
            }
        });
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        INTERFACE_OVERRIDE_CACHE.put(overridePath, pathChildrenCache);
        overrideObserver.updateConfigAll(config, overridePath,
            pathChildrenCache.getCurrentData());
    } catch (Throwable t) {
        throw new SofaRpcRuntimeException(
            "Failed to subscribe provider config from zookeeperRegistry!", t);
    }
}
 
Example 26
Source Project: kylin   Source File: ZookeeperDistributedLock.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Closeable watchLocks(String lockPathRoot, Executor executor, final Watcher watcher) {
    PathChildrenCache cache = new PathChildrenCache(curator, lockPathRoot, true);
    try {
        cache.start();
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                case CHILD_ADDED:
                    watcher.onLock(event.getData().getPath(),
                            new String(event.getData().getData(), StandardCharsets.UTF_8));
                    break;
                case CHILD_REMOVED:
                    watcher.onUnlock(event.getData().getPath(),
                            new String(event.getData().getData(), StandardCharsets.UTF_8));
                    break;
                default:
                    break;
                }
            }
        }, executor);
    } catch (Exception ex) {
        logger.error("Error to watch lock path " + lockPathRoot, ex);
    }
    return cache;
}
 
Example 27
Source Project: joyrpc   Source File: ZKRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doSubscribe(final ClusterBooking booking) {
    return Futures.call(future -> {
        ZKClusterBooking zkBooking = (ZKClusterBooking) booking;
        //添加监听
        PathChildrenCache cache = new MyPathChildrenCache(curator.unwrap(), booking.getPath(), true, () -> isOpen());
        //启动监听
        cache.start(POST_INITIALIZED_EVENT);
        zkBooking.setChildrenCache(cache);
        future.complete(null);
        cache.getListenable().addListener((client, event) -> {
            List<ShardEvent> events = new ArrayList<>();
            UpdateType type = UPDATE;
            switch (event.getType()) {
                case INITIALIZED:
                    type = FULL;
                    List<ChildData> children = event.getInitialData();
                    if (children != null) {
                        children.forEach(childData -> addEvent(events, ShardEventType.ADD, childData));
                    }
                    break;
                case CHILD_ADDED:
                    addEvent(events, ShardEventType.ADD, event.getData());
                    break;
                case CHILD_UPDATED:
                    addEvent(events, ShardEventType.UPDATE, event.getData());
                    break;
                case CHILD_REMOVED:
                    addEvent(events, ShardEventType.DELETE, event.getData());
                    break;

            }
            booking.handle(new ClusterEvent(registry, null, type, zkBooking.getStat().incrementAndGet(), events));
        });
    });
}
 
Example 28
Source Project: joyrpc   Source File: ZKRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doUnsubscribe(final ClusterBooking booking) {
    PathChildrenCache cache = ((ZKClusterBooking) booking).getChildrenCache();
    if (cache != null) {
        try {
            cache.close();
        } catch (IOException ignored) {
        }
    }
    return CompletableFuture.completedFuture(null);
}
 
Example 29
Source Project: attic-aurora   Source File: CuratorServiceGroupMonitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws MonitorException {
  try {
    // NB: This blocks on an initial group population to emulate legacy ServerSetMonitor behavior;
    // asynchronous population is an option using NORMAL or POST_INITIALIZED_EVENT StartModes
    // though.
    groupCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
  } catch (Exception e) {
    throw new MonitorException("Failed to begin monitoring service group.", e);
  }
}
 
Example 30
Source Project: octo-rpc   Source File: ZookeeperClient.java    License: Apache License 2.0 5 votes vote down vote up
protected void close() {
    try {
        stateListeners.clear();
        nodeChangeListeners.clear();
        for (PathChildrenCache wather : nodeChangeWatcher.values()) {
            wather.close();
        }
        nodeChangeWatcher.clear();
        client.close();
        logger.info("ZookeeperClient[{}] closed.", address);
    } catch (Exception e) {
        logger.error("ZookeeperClient[{}] close failed.", address, e);
    }
}