org.apache.curator.framework.recipes.cache.NodeCache Java Examples

The following examples show how to use org.apache.curator.framework.recipes.cache.NodeCache. 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 File: CuratorNodeCache.java    From yuzhouwan with Apache License 2.0 7 votes vote down vote up
public void addNodeCacheListener(String path) throws Exception {
    Stat existStat = curatorFramework
            .checkExists()
            .forPath(path);
    if (existStat == null)
        curatorFramework
                .create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.PERSISTENT)
                .forPath(path);
    NodeCache nodeCache = new NodeCache(curatorFramework, path, false);
    nodeCache.start();
    nodeCache.getListenable().addListener(() -> {
                ChildData currentData = nodeCache.getCurrentData();
                LOG.info("New Cache Data: {}", currentData == null ? "null" : new String(currentData.getData()));
            }
    );
}
 
Example #2
Source File: ZookeeperMasterMonitor.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public ZookeeperMasterMonitor(ZookeeperPaths zkPaths,
                              CuratorFramework curator,
                              MasterDescription initValue,
                              TitusRuntime titusRuntime,
                              Scheduler scheduler) {
    this.curator = curator;
    this.titusRuntime = titusRuntime;

    this.leaderPath = zkPaths.getLeaderAnnouncementPath();
    this.leaderSubject = BehaviorSubject.create(initValue).toSerialized();
    this.leaderMonitor = new NodeCache(curator, leaderPath);
    this.latestLeader.set(initValue);

    this.allMastersPath = zkPaths.getAllMastersPath();
    this.masterMonitor = new TreeCache(curator, allMastersPath);

    this.refreshOwnMasterInstanceSubscriber = ObservableExt.schedule(
            ZookeeperConstants.METRICS_ROOT + "masterMonitor.ownInstanceRefreshScheduler",
            titusRuntime.getRegistry(),
            "reRegisterOwnMasterInstanceInZookeeper",
            registerOwnMasterInstance(() -> ownMasterInstance),
            OWN_MASTER_REFRESH_INTERVAL_MS, OWN_MASTER_REFRESH_INTERVAL_MS, TimeUnit.MILLISECONDS,
            scheduler
    ).subscribe();
}
 
Example #3
Source File: ZkClient.java    From xio with Apache License 2.0 6 votes vote down vote up
public void registerUpdater(ConfigurationUpdater updater) {
  NodeCache cache = getOrCreateNodeCache(updater.getPath());
  if (client.getState().equals(CuratorFrameworkState.STARTED)) {
    startNodeCache(cache);
  }

  cache
      .getListenable()
      .addListener(
          new NodeCacheListener() {
            @Override
            public void nodeChanged() {
              updater.update(cache.getCurrentData().getData());
            }
          });
}
 
Example #4
Source File: CuratorUtil.java    From fluo with Apache License 2.0 6 votes vote down vote up
/**
 * Start watching the fluo app uuid. If it changes or goes away then halt the process.
 */
public static NodeCache startAppIdWatcher(Environment env) {
  try {
    CuratorFramework curator = env.getSharedResources().getCurator();

    byte[] uuidBytes = curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);
    if (uuidBytes == null) {
      Halt.halt("Fluo Application UUID not found");
      throw new RuntimeException(); // make findbugs happy
    }

    final String uuid = new String(uuidBytes, StandardCharsets.UTF_8);

    final NodeCache nodeCache = new NodeCache(curator, ZookeeperPath.CONFIG_FLUO_APPLICATION_ID);
    nodeCache.getListenable().addListener(() -> {
      ChildData node = nodeCache.getCurrentData();
      if (node == null || !uuid.equals(new String(node.getData(), StandardCharsets.UTF_8))) {
        Halt.halt("Fluo Application UUID has changed or disappeared");
      }
    });
    nodeCache.start();
    return nodeCache;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #5
Source File: ZookeeperConfigActivator.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
protected void subscribeIpConfig() {
    ipNodeCache = new NodeCache(zkClient, ipResourcePath);
    ipNodeCache.getListenable().addListener(new NodeCacheListener() {
        private int version = -1;

        @Override
        public void nodeChanged() throws Exception {
            if (ipNodeCache.getCurrentData() != null
                && ipNodeCache.getCurrentData().getStat().getVersion() > version) {
                version = ipNodeCache.getCurrentData().getStat().getVersion();
                String configData = new String(ipNodeCache.getCurrentData().getData());
                ipConfigDeque.add(configData);
                LOGGER.info("Receive ip config data: {}, version is {}.", configData, version);
            }
        }
    });
    try {
        LOGGER.info("Subscribe ip config: {}.", ipResourcePath);
        ipNodeCache.start(true);
    } catch (Exception e) {
        throw new ArkRuntimeException("Failed to subscribe ip resource path.", e);
    }
}
 
Example #6
Source File: ZookeeperConfigActivator.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
protected void subscribeBizConfig() {
    bizNodeCache = new NodeCache(zkClient, bizResourcePath);
    bizNodeCache.getListenable().addListener(new NodeCacheListener() {
        private int version = -1;

        @Override
        public void nodeChanged() throws Exception {
            if (bizNodeCache.getCurrentData() != null
                && bizNodeCache.getCurrentData().getStat().getVersion() > version) {
                version = bizNodeCache.getCurrentData().getStat().getVersion();
                String configData = new String(bizNodeCache.getCurrentData().getData());
                bizConfigDeque.add(configData);
                LOGGER.info("Receive app config data: {}, version is {}.", configData, version);
            }
        }
    });

    try {
        bizNodeCache.start(true);
    } catch (Exception e) {
        throw new ArkRuntimeException("Failed to subscribe resource path.", e);
    }
}
 
Example #7
Source File: NodeCacheObserver.java    From micro-service with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        CuratorFramework client = CuratorFrameworkFactory.newClient(ZOOKEEPER_CONNECT_STRING, new ExponentialBackoffRetry(1000, 3));
        client.start();

        String path = client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL).forPath("/observer", "data".getBytes());
        final NodeCache nodeCache = new NodeCache(client, path, false);
        nodeCache.start();

        nodeCache.getListenable().addListener(new NodeCacheListener() {
            public void nodeChanged() throws Exception {
                if (nodeCache.getCurrentData() != null) {
                    logger.info(nodeCache.getPath());
                }
            }
        });
    }
 
Example #8
Source File: ConfigBusConsumer.java    From eagle with Apache License 2.0 6 votes vote down vote up
public ConfigBusConsumer(ZKConfig config, String topic, ConfigChangeCallback callback) {
    super(config);
    this.zkPath = zkRoot + "/" + topic;
    LOG.info("monitor change for zkPath " + zkPath);
    cache = new NodeCache(curator, zkPath);
    cache.getListenable().addListener(() -> {
        ConfigValue v = getConfigValue();
        callback.onNewConfig(v);
    }
    );
    try {
        cache.start();
    } catch (Exception ex) {
        LOG.error("error start NodeCache listener", ex);
        throw new RuntimeException(ex);
    }
}
 
Example #9
Source File: ZKSegmentContainerMonitor.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of ZKSegmentContainerMonitor.
 *
 * @param containerRegistry      The registry used to control the container state.
 * @param zkClient               The curator client.
 * @param pravegaServiceEndpoint The pravega endpoint for which we need to fetch the container assignment.
 */
ZKSegmentContainerMonitor(SegmentContainerRegistry containerRegistry, CuratorFramework zkClient,
                          Host pravegaServiceEndpoint, int parallelContainerStarts, ScheduledExecutorService executor) {
    Preconditions.checkNotNull(zkClient, "zkClient");
    Preconditions.checkArgument(parallelContainerStarts > 0, "parallelContainerStarts");

    this.registry = Preconditions.checkNotNull(containerRegistry, "containerRegistry");
    this.host = Preconditions.checkNotNull(pravegaServiceEndpoint, "pravegaServiceEndpoint");
    this.executor = Preconditions.checkNotNull(executor, "executor");
    this.handles = new ConcurrentHashMap<>();
    this.pendingTasks = new ConcurrentSkipListSet<>();
    String clusterPath = ZKPaths.makePath("cluster", "segmentContainerHostMapping");
    this.hostContainerMapNode = new NodeCache(zkClient, clusterPath);
    this.assignmentTask = new AtomicReference<>();
    this.lastReportTime = new AtomicLong(CURRENT_TIME_MILLIS.get());
    this.parallelContainerStartsSemaphore = new Semaphore(parallelContainerStarts);
}
 
Example #10
Source File: ZookeeperConfigService.java    From Zebra with Apache License 2.0 6 votes vote down vote up
private NodeCache newNodeCache(final String key) throws Exception {
	String path = getConfigPath(key);
	final NodeCache nodeCache = new NodeCache(client, path);
	nodeCache.getListenable().addListener(new NodeCacheListener() {
		@Override
		public void nodeChanged() throws Exception {
			String oldValue = keyMap.get(key);
			String newValue = new String(nodeCache.getCurrentData().getData());
			keyMap.put(key, newValue);
			notifyListeners(key, oldValue, newValue);
		}
	});
	nodeCache.start(true);

	keyMap.put(key, new String(nodeCache.getCurrentData().getData(), Constants.DEFAULT_CHARSET));

	return nodeCache;
}
 
Example #11
Source File: ZktoXmlMain.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 进行zk的watch操作
* 方法描述
* @param zkConn zk的连接信息
* @param path 路径信息
* @param zkListen 监控路径信息
* @throws Exception
* @创建日期 2016年9月20日
*/
private static NodeCache runWatch(final CuratorFramework zkConn, final String path,
        final ZookeeperProcessListen zkListen) throws Exception {
    final NodeCache cache = new NodeCache(zkConn, path);

    NodeCacheListener listen = new NodeCacheListener() {
        @Override
        public void nodeChanged() throws Exception {
            LOGGER.info("ZktoxmlMain runWatch  process path  event start ");
            LOGGER.info("NodeCache changed, path is: " + cache.getCurrentData().getPath());
            String notPath = cache.getCurrentData().getPath();
            // 进行通知更新
            zkListen.notifly(notPath);
            LOGGER.info("ZktoxmlMain runWatch  process path  event over");
        }
    };

    // 添加监听
    cache.getListenable().addListener(listen);

    return cache;
}
 
Example #12
Source File: ZkClient.java    From xio with Apache License 2.0 5 votes vote down vote up
public void stopNodeCache(NodeCache cache) {
  try {
    cache.close();
  } catch (IOException e) {
    log.error("Error stopping nodeCache {}", cache, e);
    throw new RuntimeException(e);
  }
}
 
Example #13
Source File: NodeCacheExample.java    From ZKRecipesByExample with Apache License 2.0 5 votes vote down vote up
private static void addListener(final NodeCache cache) {
	// a PathChildrenCacheListener is optional. Here, it's used just to log
	// changes
	NodeCacheListener listener = new NodeCacheListener() {

		@Override
		public void nodeChanged() throws Exception {
			if (cache.getCurrentData() != null)
				System.out.println("Node changed: " + cache.getCurrentData().getPath() + ", value: " + new String(cache.getCurrentData().getData()));
		}
	};
	cache.getListenable().addListener(listener);
}
 
Example #14
Source File: ZookeeperNodeCacheListener.java    From Thunder with Apache License 2.0 5 votes vote down vote up
public ZookeeperNodeCacheListener(CuratorFramework client, String path) throws Exception {
    super(client, path);

    nodeCache = new NodeCache(client, path, false);
    nodeCache.start(true);

    addListener();
}
 
Example #15
Source File: CuratorClientService.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void removeEntryListener(String path) throws Exception {
    NodeCache nodeCache = entryNodeCaches.remove(path);
    if (nodeCache != null) {
        nodeCache.close();
    }
}
 
Example #16
Source File: CustomizationRegistry.java    From Pistachio with Apache License 2.0 5 votes vote down vote up
public void init() {
    try
    {
        logger.info("init...");
        client = CuratorFrameworkFactory.newClient(
            ConfigurationManager.getConfiguration().getString(ZOOKEEPER_SERVER),
            new ExponentialBackoffRetry(1000, 3));
        client.start();

        // in this example we will cache data. Notice that this is optional.
        cache = new NodeCache(client, getZKPath());
        cache.start();

        cache.getListenable().addListener(this);

        nodeChanged();

    } catch (Exception e) {
        logger.info("error ", e);
    }
    /*
    finally
    {
        CloseableUtils.closeQuietly(cache);
        CloseableUtils.closeQuietly(client);
    }
    */
}
 
Example #17
Source File: ZooKeeperScanPolicyObserver.java    From hbase with Apache License 2.0 5 votes vote down vote up
private void create() throws Exception {
  client =
      CuratorFrameworkFactory.builder().connectString(ensemble).sessionTimeoutMs(sessionTimeout)
          .retryPolicy(new RetryForever(1000)).canBeReadOnly(true).build();
  client.start();
  cache = new NodeCache(client, NODE);
  cache.start(true);
}
 
Example #18
Source File: ZooKeeperScanPolicyObserver.java    From hbase with Apache License 2.0 5 votes vote down vote up
public synchronized NodeCache acquire() throws Exception {
  if (ref == 0) {
    try {
      create();
    } catch (Exception e) {
      close();
      throw e;
    }
  }
  ref++;
  return cache;
}
 
Example #19
Source File: ZkClient.java    From xio with Apache License 2.0 5 votes vote down vote up
public void startNodeCache(NodeCache cache) {
  try {
    cache.start();
  } catch (Exception e) {
    log.error("Error starting nodeCache {}", cache, e);
    throw new RuntimeException(e);
  }
}
 
Example #20
Source File: CuratorClientService.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void addEntryListener(String path, EntryListener listener) throws Exception {
    NodeCache nodeCache = new NodeCache(delegate, path);
    nodeCache.getListenable().addListener(new EntryListenerAdapter(this, nodeCache, listener));
    nodeCache.start();
    entryNodeCaches.put(path, nodeCache);
}
 
Example #21
Source File: ZKGarbageCollector.java    From pravega with Apache License 2.0 5 votes vote down vote up
@SneakyThrows(Exception.class)
private NodeCache registerWatch(String watchPath) {
    NodeCache nodeCache = new NodeCache(zkStoreHelper.getClient(), watchPath);
    NodeCacheListener watchListener = () -> {
        currentBatch.set(nodeCache.getCurrentData().getStat().getVersion());
        log.debug("Current batch for {} changed to {}", gcName, currentBatch.get());
    };

    nodeCache.getListenable().addListener(watchListener);

    nodeCache.start();
    return nodeCache;
}
 
Example #22
Source File: NodeCacheExample.java    From ZKRecipesByExample with Apache License 2.0 5 votes vote down vote up
private static void processCommands(CuratorFramework client, NodeCache cache) throws Exception {
	printHelp();
	try {
		addListener(cache);
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		boolean done = false;
		while (!done) {
			System.out.print("> ");
			String line = in.readLine();
			if (line == null) {
				break;
			}
			String command = line.trim();
			String[] parts = command.split("\\s");
			if (parts.length == 0) {
				continue;
			}
			String operation = parts[0];
			String args[] = Arrays.copyOfRange(parts, 1, parts.length);
			if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) {
				printHelp();
			} else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) {
				done = true;
			} else if (operation.equals("set")) {
				setValue(client, command, args);
			} else if (operation.equals("remove")) {
				remove(client);
			} else if (operation.equals("show")) {
				show(cache);
			}
			Thread.sleep(1000); // just to allow the console output to catch
								// up
		}
	} catch (Exception ex) {
		ex.printStackTrace();
	} finally {

	}
}
 
Example #23
Source File: DistributedConfigurationManager.java    From oodt with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link CuratorFramework} instance and start it. This method will wait a maximum amount of {@link
 * Properties#ZK_STARTUP_TIMEOUT} milli-seconds until the client connects to the zookeeper ensemble.
 */
private void startZookeeper() {
    client = CuratorUtils.newCuratorFrameworkClient(connectString, logger);
    client.start();
    logger.info("Curator framework start operation invoked");

    int startupTimeOutMs = Integer.parseInt(System.getProperty(ZK_STARTUP_TIMEOUT, "30000"));
    try {
        logger.info("Waiting to connect to zookeeper, startupTimeout : {}", startupTimeOutMs);
        client.blockUntilConnected(startupTimeOutMs, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        logger.error("Interrupted while waiting to connect zookeeper (connectString : {}) : {}", ex, connectString);
    }

    if (!client.getZookeeperClient().isConnected()) {
        throw new IllegalStateException("Could not connect to ZooKeeper : " + connectString);
    }

    logger.info("CuratorFramework client started successfully");

    nodeCache = new NodeCache(client, zNodePaths.getNotificationsZNodePath());
    nodeCache.getListenable().addListener(nodeCacheListener);
    try {
        logger.debug("Starting NodeCache to watch for configuration changes");
        nodeCache.start(true);
    } catch (Exception e) {
        logger.error("Error occurred when start listening for configuration changes", e);
        throw new IllegalStateException("Unable to start listening for configuration changes", e);
    }
    logger.info("NodeCache for watching configuration changes started successfully");
}
 
Example #24
Source File: ZookeeperConfigService.java    From Zebra with Apache License 2.0 5 votes vote down vote up
private String loadKeyFromNodeCache(final String key) throws Exception {
	NodeCache nodeCache = nodeCacheMap.get(key);

	if (nodeCache == null) {
		nodeCache = newNodeCache(key);
		nodeCacheMap.put(key, nodeCache);
	}

	byte[] data = nodeCache.getCurrentData().getData();
	return new String(data, Constants.DEFAULT_CHARSET);
}
 
Example #25
Source File: ZkValueStore.java    From emodb with Apache License 2.0 5 votes vote down vote up
public ZkValueStore(CuratorFramework curator, String zkPath, ZkValueSerializer<T> serializer, T defaultValue) {
    _curator = checkNotNull(curator, "curator");
    _zkPath = checkNotNull(zkPath, "zkPath");
    _serializer = checkNotNull(serializer, "serializer");
    _nodeCache = new NodeCache(curator, zkPath);
    _defaultValue = defaultValue;
    // Create node on instantiation
    // In practice, this creates a persistent zookeeper node without having to start the Managed resource.
    try {
        createNode();
    } catch (Exception e) {
        // Log a warning. We will try again when Managed is started
        _log.warn(format("Could not create node %s", _zkPath));
    }
}
 
Example #26
Source File: MountsManager.java    From nnproxy with Apache License 2.0 5 votes vote down vote up
@Override
protected void serviceStart() throws Exception {
    framework.start();
    nodeCache = new NodeCache(framework, zkMountTablePath, false);
    nodeCache.getListenable().addListener(new NodeCacheListener() {
        @Override
        public void nodeChanged() throws Exception {
            handleMountTableChange(nodeCache.getCurrentData().getData());
        }
    });
    nodeCache.start(false);
}
 
Example #27
Source File: SyncSwitch.java    From canal with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
private synchronized void startListen(String destination, BooleanMutex mutex) {
    try {
        String path = SYN_SWITCH_ZK_NODE + destination;
        CuratorFramework curator = curatorClient.getCurator();
        NodeCache nodeCache = new NodeCache(curator, path);
        nodeCache.start();
        nodeCache.getListenable().addListener(() -> initMutex(curator, destination, mutex));
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example #28
Source File: TSOClient.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
private void configureCurrentTSOServerZNodeCache(String currentTsoPath) {
    try {
        currentTSOZNode = new NodeCache(zkClient, currentTsoPath);
        currentTSOZNode.getListenable().addListener(this);
        currentTSOZNode.start(true);
    } catch (Exception e) {
        throw new IllegalStateException("Cannot start watcher on current TSO Server ZNode: " + e.getMessage());
    }
}
 
Example #29
Source File: ZooKeeperLeaderElectionService.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ZooKeeperLeaderElectionService object.
 *
 * @param client Client which is connected to the ZooKeeper quorum
 * @param latchPath ZooKeeper node path for the leader election latch
 * @param leaderPath ZooKeeper node path for the node which stores the current leader information
 */
public ZooKeeperLeaderElectionService(CuratorFramework client, String latchPath, String leaderPath) {
	this.client = Preconditions.checkNotNull(client, "CuratorFramework client");
	this.leaderPath = Preconditions.checkNotNull(leaderPath, "leaderPath");

	leaderLatch = new LeaderLatch(client, latchPath);
	cache = new NodeCache(client, leaderPath);

	issuedLeaderSessionID = null;
	confirmedLeaderSessionID = null;
	leaderContender = null;

	running = false;
}
 
Example #30
Source File: ZKHostStore.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Zookeeper based host store implementation.
 *
 * @param client                    The curator client instance.
 */
ZKHostStore(CuratorFramework client, int containerCount) {
    Preconditions.checkNotNull(client, "client");

    zkClient = client;
    zkPath = ZKPaths.makePath("cluster", "segmentContainerHostMapping");
    segmentMapper = new SegmentToContainerMapper(containerCount);
    hostContainerMapNode = new NodeCache(zkClient, zkPath);
    hostContainerMap = new AtomicReference<>(HostContainerMap.EMPTY);
    listenerRef = new AtomicReference<>();
}