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

The following examples show how to use org.apache.curator.framework.recipes.cache.NodeCache. 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: sofa-ark   Source File: ZookeeperConfigActivator.java    License: 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 2
Source Project: sofa-ark   Source File: ZookeeperConfigActivator.java    License: 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 3
Source Project: Mycat2   Source File: ZktoXmlMain.java    License: 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 4
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 5
Source Project: Zebra   Source File: ZookeeperConfigService.java    License: 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 6
Source Project: pravega   Source File: ZKSegmentContainerMonitor.java    License: 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 7
Source Project: eagle   Source File: ConfigBusConsumer.java    License: 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 8
Source Project: micro-service   Source File: NodeCacheObserver.java    License: 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 9
Source Project: yuzhouwan   Source File: CuratorNodeCache.java    License: Apache License 2.0 6 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 10
Source Project: xio   Source File: ZkClient.java    License: 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 11
Source Project: fluo   Source File: CuratorUtil.java    License: 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 12
/**
 * 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 13
/**
 * Creates a leader retrieval service which uses ZooKeeper to retrieve the leader information.
 *
 * @param client Client which constitutes the connection to the ZooKeeper quorum
 * @param retrievalPath Path of the ZooKeeper node which contains the leader information
 */
public ZooKeeperLeaderRetrievalService(CuratorFramework client, String retrievalPath) {
	this.client = Preconditions.checkNotNull(client, "CuratorFramework client");
	this.cache = new NodeCache(client, retrievalPath);
	this.retrievalPath = Preconditions.checkNotNull(retrievalPath);

	this.leaderListener = null;
	this.lastLeaderAddress = null;
	this.lastLeaderSessionID = null;

	running = false;
}
 
Example 14
Source Project: flink   Source File: ZooKeeperLeaderElectionService.java    License: 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 15
Source Project: flink   Source File: ZooKeeperLeaderRetrievalService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a leader retrieval service which uses ZooKeeper to retrieve the leader information.
 *
 * @param client Client which constitutes the connection to the ZooKeeper quorum
 * @param retrievalPath Path of the ZooKeeper node which contains the leader information
 */
public ZooKeeperLeaderRetrievalService(CuratorFramework client, String retrievalPath) {
	this.client = Preconditions.checkNotNull(client, "CuratorFramework client");
	this.cache = new NodeCache(client, retrievalPath);
	this.retrievalPath = Preconditions.checkNotNull(retrievalPath);

	this.leaderListener = null;
	this.lastLeaderAddress = null;
	this.lastLeaderSessionID = null;

	running = false;
}
 
Example 16
Source Project: DDMQ   Source File: ConfigUpdate.java    License: Apache License 2.0 5 votes vote down vote up
public boolean init() {
    if (StringUtils.isEmpty(controller.getBrokerConfig().getZkPath())) {
        return true;
    }

    client = CuratorFrameworkFactory.newClient(controller.getBrokerConfig().getZkPath(), new ExponentialBackoffRetry(1000, 3));
    client.start();

    String path = getBrokerConfigPath();
    try {
        if (client.checkExists().forPath(path) == null) {
            log.error("config path in not exist, path:{}", path);
            return false;
        }
        //add watcher
        cache = new NodeCache(client, path);
        NodeCacheListener listener = new NodeCacheListener() {
            @Override public void nodeChanged() throws Exception {
                log.info("config changed, update");
                ChildData data = cache.getCurrentData();
                if (null != data) {
                    String config = new String(cache.getCurrentData().getData());
                    updateConfig(config);
                } else {
                    log.warn("node is deleted");
                }
            }
        };

        cache.getListenable().addListener(listener);

        cache.start();
    } catch (Exception ex) {
        log.error("cache start failed", ex);
        return false;
    }

    return true;
}
 
Example 17
Source Project: canal-1.1.3   Source File: SyncSwitch.java    License: 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 18
Source Project: joyrpc   Source File: ZKRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doSubscribe(final ConfigBooking booking) {
    return Futures.call(future -> {
        ZKConfigBooking zkBooking = (ZKConfigBooking) booking;
        CuratorFramework client = curator.unwrap();
        Stat pathStat = client.checkExists().creatingParentsIfNeeded().forPath(booking.getPath());
        if (pathStat == null) {
            client.create().creatingParentsIfNeeded().forPath(booking.getPath(), new byte[0]);
        }
        NodeCache cache = new MyNodeCache(client, booking.getPath(), () -> isOpen());
        cache.start();
        zkBooking.setNodeCache(cache);
        future.complete(null);
        cache.getListenable().addListener(() -> {
            ChildData childData = cache.getCurrentData();
            Map<String, String> datum;
            if (childData == null) {
                //被删掉了
                datum = new HashMap<>();
            } else {
                byte[] data = childData.getData();
                if (data != null && data.length > 0) {
                    datum = JSON.get().parseObject(new String(data, UTF_8), Map.class);
                } else {
                    datum = new HashMap<>();
                }
            }
            booking.handle(new ConfigEvent(registry, null, zkBooking.getStat().incrementAndGet(), datum));
        });
    });
}
 
Example 19
Source Project: joyrpc   Source File: ZKRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doUnsubscribe(final ConfigBooking booking) {
    NodeCache cache = ((ZKConfigBooking) booking).getNodeCache();
    if (cache != null) {
        try {
            cache.close();
        } catch (IOException ignored) {
        }
    }
    return CompletableFuture.completedFuture(null);
}
 
Example 20
Source Project: BigData-In-Practice   Source File: CuratorWatcher.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    final String nodePath = "/testZK";
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(10000, 5);
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(zkServerIps)
            .sessionTimeoutMs(10000).retryPolicy(retryPolicy).build();
    try {
        client.start();
        client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(nodePath, "this is a test data".getBytes());

        final NodeCache cacheNode = new NodeCache(client, nodePath, false);
        cacheNode.start(true);  // true 表示启动时立即从Zookeeper上获取节点
        cacheNode.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("节点数据更新,新的内容是: " + new String(cacheNode.getCurrentData().getData()));
            }
        });
        for (int i = 0; i < 5; i++) {
            client.setData().forPath(nodePath, ("new test data " + i).getBytes());
            Thread.sleep(1000);
        }
        Thread.sleep(10000); // 等待100秒,手动在 zkCli 客户端操作节点,触发事件
    } finally {
        client.delete().deletingChildrenIfNeeded().forPath(nodePath);
        client.close();
        System.out.println("客户端关闭......");
    }
}
 
Example 21
Source Project: xian   Source File: ZkKeyValueCacheUtil.java    License: Apache License 2.0 5 votes vote down vote up
public Pair<NodeCache, String> load(String subPath) throws Exception {
    NodeCache nodeCache = createNodeCache(subPath);
    if (ZkConnection.client.checkExists().forPath(getFullPath(subPath)) == null) {
        //创建节点是异步动作,因此有这个检查
        return Pair.of(nodeCache, "");
    }
    return Pair.of(nodeCache, new String(ZkConnection.client.getData().forPath(getFullPath(subPath))));
}
 
Example 22
Source Project: xian   Source File: ZkKeyValueCacheUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static NodeCache createNodeCache(String subPath) {
    String fullPath = getFullPath(subPath);
    NodeCache nodeCache = new NodeCache(ZkConnection.client, fullPath);
    try {
        nodeCache.start();
    } catch (Exception e) {
        LOG.error(e);
    }
    nodeCache.getListenable().addListener(() -> {
        String newDataStr = new String(nodeCache.getCurrentData().getData());
        LOG.info("监听到zk缓存取值有变化:" + fullPath + "=" + newDataStr);
        loadingCache.get(subPath).snd = newDataStr;
    }/*, ThreadPoolManager.getExecutor()*/);
    return nodeCache;
}
 
Example 23
Source Project: DDMQ   Source File: ConfigUpdate.java    License: Apache License 2.0 5 votes vote down vote up
public boolean init() {
    if (StringUtils.isEmpty(controller.getBrokerConfig().getZkPath())) {
        return true;
    }

    client = CuratorFrameworkFactory.newClient(controller.getBrokerConfig().getZkPath(), new ExponentialBackoffRetry(1000, 3));
    client.start();

    String path = getBrokerConfigPath();
    try {
        if (client.checkExists().forPath(path) == null) {
            log.error("config path in not exist, path:{}", path);
            return false;
        }
        //add watcher
        cache = new NodeCache(client, path);
        NodeCacheListener listener = new NodeCacheListener() {
            @Override public void nodeChanged() throws Exception {
                log.info("config changed, update");
                ChildData data = cache.getCurrentData();
                if (null != data) {
                    String config = new String(cache.getCurrentData().getData());
                    updateConfig(config);
                } else {
                    log.warn("node is deleted");
                }
            }
        };

        cache.getListenable().addListener(listener);

        cache.start();
    } catch (Exception ex) {
        log.error("cache start failed", ex);
        return false;
    }

    return true;
}
 
Example 24
Source Project: hermes   Source File: FollowerInitEventHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void start() {
	startScheduledExecutor();
	try {
		m_baseMetaVersionCache = new NodeCache(m_zkClient.get(), ZKPathUtils.getBaseMetaVersionZkPath());
		m_baseMetaVersionCache.start(true);

		m_leaderMetaVersionCache = new NodeCache(m_zkClient.get(), ZKPathUtils.getMetaInfoZkPath());
		m_leaderMetaVersionCache.start(true);
	} catch (Exception e) {
		throw new RuntimeException(String.format("Init {} failed.", getName()), e);
	}

}
 
Example 25
Source Project: Mycat2   Source File: ZktoXmlMain.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void loadZkWatch(Set<String> setPaths, final CuratorFramework zkConn,
        final ZookeeperProcessListen zkListen) throws Exception {

    if (null != setPaths && !setPaths.isEmpty()) {
        for (String path : setPaths) {
            // 进行本地节点的监控操作
            NodeCache node = runWatch(zkConn, path, zkListen);
            node.start();

            LOGGER.info("ZktoxmlMain loadZkWatch path:" + path + " regist success");
        }
    }
}
 
Example 26
Source Project: dble   Source File: ZktoXmlMain.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void loadZkWatch(Set<String> setPaths, final CuratorFramework zkConn,
                                final ZookeeperProcessListen zkListen) throws Exception {
    if (null != setPaths && !setPaths.isEmpty()) {
        for (String path : setPaths) {
            final NodeCache node = new NodeCache(zkConn, path);
            node.start(true);
            runWatch(node, zkListen);
            LOGGER.info("ZktoxmlMain loadZkWatch path:" + path + " regist success");
        }
    }
}
 
Example 27
Source Project: dble   Source File: ZktoXmlMain.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void runWatch(final NodeCache cache, final ZookeeperProcessListen zkListen)
        throws Exception {
    cache.getListenable().addListener(new NodeCacheListener() {

        @Override
        public void nodeChanged() {
            LOGGER.info("ZktoxmlMain runWatch  process path  event start ");
            String notPath = cache.getCurrentData().getPath();
            LOGGER.info("NodeCache changed, path is: " + notPath);
            // notify
            zkListen.notify(notPath);
            LOGGER.info("ZktoxmlMain runWatch  process path  event over");
        }
    });
}
 
Example 28
Source Project: phoenix-omid   Source File: TSOClient.java    License: 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 Project: nnproxy   Source File: MountsManager.java    License: 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 30
Source Project: emodb   Source File: ZkValueStore.java    License: 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));
    }
}