Java Code Examples for org.apache.curator.framework.recipes.cache.NodeCache#start()

The following examples show how to use org.apache.curator.framework.recipes.cache.NodeCache#start() . 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: 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 3
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 4
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 5
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 6
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 7
Source File: ZktoXmlMain.java    From dble with 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 8
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 9
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 10
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 11
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 12
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 13
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 14
Source File: ZktoXmlMain.java    From Mycat2 with 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 15
Source File: FollowerInitEventHandler.java    From hermes with 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 16
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 17
Source File: CuratorWatcher.java    From BigData-In-Practice with 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 18
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 19
Source File: TestEndToEndScenariosWithHA.java    From phoenix-omid with Apache License 2.0 4 votes vote down vote up
@BeforeMethod(alwaysRun = true, timeOut = 30_000)
public void setup() throws Exception {
    // Get the zkConnection string from minicluster
    String zkConnection = "localhost:" + hBaseUtils.getZkCluster().getClientPort();

    zkClient = provideInitializedZookeeperClient(zkConnection);

    // Synchronize TSO start
    barrierTillTSOAddressPublication = new CountDownLatch(1);
    final NodeCache currentTSOZNode = new NodeCache(zkClient, CURRENT_TSO_PATH);
    currentTSOZNode.getListenable().addListener(new NodeCacheListener() {

        @Override
        public void nodeChanged() throws Exception {
            byte[] currentTSOAndEpochAsBytes = currentTSOZNode.getCurrentData().getData();
            String currentTSOAndEpoch = new String(currentTSOAndEpochAsBytes, Charsets.UTF_8);
            if (currentTSOAndEpoch.endsWith("#0")) { // Wait till a TSO instance publishes the epoch
                barrierTillTSOAddressPublication.countDown();
            }
        }

    });
    currentTSOZNode.start(true);

    // Configure TSO 1
    TSOServerConfig config1 = new TSOServerConfig();
    config1.setPort(TSO1_PORT);
    config1.setConflictMapSize(1000);
    config1.setLeaseModule(new TestHALeaseManagementModule(TEST_LEASE_PERIOD_MS, TSO_LEASE_PATH, CURRENT_TSO_PATH, zkConnection, NAMESPACE));
    Injector injector1 = Guice.createInjector(new TestTSOModule(hbaseConf, config1));
    LOG.info("===================== Starting TSO 1 =====================");
    tso1 = injector1.getInstance(TSOServer.class);
    leaseManager1 = (PausableLeaseManager) injector1.getInstance(LeaseManagement.class);
    tso1.startAndWait();
    TestUtils.waitForSocketListening("localhost", TSO1_PORT, 100);
    LOG.info("================ Finished loading TSO 1 ==================");

    // Configure TSO 2
    TSOServerConfig config2 = new TSOServerConfig();
    config2.setPort(TSO2_PORT);
    config2.setConflictMapSize(1000);
    config2.setLeaseModule(new TestHALeaseManagementModule(TEST_LEASE_PERIOD_MS, TSO_LEASE_PATH, CURRENT_TSO_PATH, zkConnection, NAMESPACE));
    Injector injector2 = Guice.createInjector(new TestTSOModule(hbaseConf, config2));
    LOG.info("===================== Starting TSO 2 =====================");
    tso2 = injector2.getInstance(TSOServer.class);
    injector2.getInstance(LeaseManagement.class);
    tso2.startAndWait();
    // Don't do this here: TestUtils.waitForSocketListening("localhost", 4321, 100);
    LOG.info("================ Finished loading TSO 2 ==================");

    // Wait till the master TSO is up
    barrierTillTSOAddressPublication.await();
    currentTSOZNode.close();

    // Configure HBase TM
    LOG.info("===================== Starting TM =====================");
    HBaseOmidClientConfiguration hbaseOmidClientConf = new HBaseOmidClientConfiguration();
    hbaseOmidClientConf.setConnectionType(HA);
    hbaseOmidClientConf.setConnectionString(zkConnection);
    hbaseOmidClientConf.getOmidClientConfiguration().setZkCurrentTsoPath(CURRENT_TSO_PATH);
    hbaseOmidClientConf.getOmidClientConfiguration().setZkNamespace(NAMESPACE);
    hbaseOmidClientConf.setHBaseConfiguration(hbaseConf);
    hbaseConf.setInt(HBASE_CLIENT_RETRIES_NUMBER, 3);
    tm = HBaseTransactionManager.builder(hbaseOmidClientConf).build();
    LOG.info("===================== TM Started =========================");
}
 
Example 20
Source File: ServiceDiscoveryImpl.java    From xian with Apache License 2.0 4 votes vote down vote up
private NodeCache makeNodeCache(final ServiceInstance<T> instance)
{
    if ( !watchInstances )
    {
        return null;
    }

    final NodeCache nodeCache = new NodeCache(client, pathForInstance(instance.getName(), instance.getId()));
    try
    {
        nodeCache.start(true);
    }
    catch ( Exception e )
    {
        ThreadUtils.checkInterrupted(e);
        log.error("Could not start node cache for: " + instance, e);
    }
    NodeCacheListener listener = new NodeCacheListener()
    {
        @Override
        public void nodeChanged() throws Exception
        {
            if ( nodeCache.getCurrentData() != null )
            {
                ServiceInstance<T> newInstance = serializer.deserialize(nodeCache.getCurrentData().getData());
                Entry<T> entry = services.get(newInstance.getId());
                if ( entry != null )
                {
                    synchronized(entry)
                    {
                        entry.service = newInstance;
                    }
                }
            }
            else
            {
                log.warn("Instance data has been deleted for: " + instance);
            }
        }
    };
    nodeCache.getListenable().addListener(listener);
    return nodeCache;
}