private void startClient() { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); curator = builder.connectString(zkServers).retryPolicy(new ExponentialBackoffRetry(1000,100)).build(); curator.getConnectionStateListenable().addListener(this); curator.start(); }
@Override public void close() { if (clusterId != null) { client.getConnectionStateListenable().removeListener(connectionStateListener); } client.close(); }
public static void main(String[] args) throws Exception { TestingServer server = new TestingServer(); CuratorFramework client = null; SimpleDistributedQueue queue = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); client.getCuratorListenable().addListener(new CuratorListener() { @Override public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { client.start(); queue = new SimpleDistributedQueue(client, PATH); for (int i = 0; i < 10; i++) { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(server);
public static void main(String[] args) throws Exception { TestingServer server = new TestingServer(); CuratorFramework client = null; PersistentNode node = null; try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); client.getConnectionStateListenable().addListener(new ConnectionStateListener() { client.start(); node.waitForInitialCreate(3, TimeUnit.SECONDS); String actualPath = node.getActualPath(); System.out.println("node " + actualPath + " value: " + new String(client.getData().forPath(actualPath))); client.create().forPath(PATH2, "persistent node".getBytes()); ex.printStackTrace(); } finally { CloseableUtils.closeQuietly(node); CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(server);
@Override public void connectToRegistryServer(String connectString) { checkNotNull(connectString, "connectString"); configClient = CuratorFrameworkFactory.newClient( connectString, sessionTimeoutMs, connectionTimeoutMs, new ExponentialBackoffRetry(500, 20)); configClient.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { logger.info("Zookeeper connection state changed {}.", newState); if (newState == ConnectionState.RECONNECTED) { logger.info("Zookeeper connection has been re-established, will re-subscribe and re-register."); // 重新订阅 for (RegisterMeta.ServiceMeta serviceMeta : getSubscribeSet()) { doSubscribe(serviceMeta); } // 重新发布服务 for (RegisterMeta meta : getRegisterMetaMap().keySet()) { ZookeeperRegistryService.super.register(meta); } } } }); configClient.start(); }
@Test(timeout = 60_000L) public void testSessionKilled() throws Exception curator.start(); curator.blockUntilConnected(); Announcer announcer = new Announcer(curator, exec); try { curator.inTransaction().create().forPath("/somewhere").and().commit(); announcer.start(); curator.getCuratorListenable().addListener( new CuratorListener() KillSession.kill(curator.getZookeeperClient().getZooKeeper(), server.getConnectString());
); curator.start(); curator.blockUntilConnected(); curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/container/billy", new byte[]{}); curator.getCuratorListenable().addListener( new CuratorListener() { @Override server.stop(); Assert.assertTrue(timing.awaitLatch(latch));
@Test(timeout = 60_000L) public void testSanity() throws Exception curator.start(); curator.blockUntilConnected(); Announcer announcer = new Announcer(curator, exec); announcer.initializeAddedChildren(); announcer.announce(testPath1, billy); Assert.assertNull("/test1 does not exists", curator.checkExists().forPath(testPath1)); Assert.assertNull("/somewhere/test2 does not exists", curator.checkExists().forPath(testPath2)); curator.getCuratorListenable().addListener( new CuratorListener()
public boolean newZkClient() throws InterruptedException { CuratorFramework client = CuratorFrameworkFactory.builder() .ensembleProvider(new DefaultEnsembleProvider(address)) .sessionTimeoutMs(30 * 1000) .connectionTimeoutMs(15 * 1000) .retryPolicy(new ExponentialBackoffRetry(1000, Integer.MAX_VALUE)) .build(); client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { LOGGER.info("zookeeper state changed to " + newState); if (newState == ConnectionState.RECONNECTED) { // RegistryEventListener.connectionReconnected(); } } }); //事件监听; client.getCuratorListenable().addListener(new CuratorEventListener(this), curatorEventListenerThreadPool); client.start(); boolean isConnected = client.getZookeeperClient().blockUntilConnectedOrTimedOut(); CuratorFramework oldClient = this.zookeeperClient; this.zookeeperClient = client; close(oldClient); LOGGER.info("succeed to create zookeeper curator, connected:" + isConnected); return isConnected; }
@Override public void start() { if (client.getState() != CuratorFrameworkState.STARTED) { client.start(); if (clusterId != null) { client.getConnectionStateListenable().addListener(connectionStateListener); checkClusterIdExists(clusterId, "start"); } } }
CuratorFrameworkFactory.Builder zkClientuilder = CuratorFrameworkFactory.builder() .connectString(address) .sessionTimeoutMs(registryConfig.getConnectTimeout() * 3) zkClient.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) {
public synchronized void stop() throws Exception { if (started) { isLeader = false; server.stop(); serverThread.join(); if (gcTsTracker != null) { gcTsTracker.stop(); } started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderLatch.close(); execService.shutdown(); execService.awaitTermination(10, TimeUnit.SECONDS); curatorFramework.getConnectionStateListenable().removeListener(cnxnListener); // leaderLatch.close() schedules a background delete, give it a chance to process before // closing curator... this is done to avoid spurious exceptions, see CURATOR-467 Uninterruptibles.sleepUninterruptibly(250, TimeUnit.MILLISECONDS); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }
private void start() throws Exception{ curaFramework = CuratorFrameworkFactory.newClient(getZkConnectString(), new ExponentialBackoffRetry(1000, 3)); curaFramework.start(); curaFramework.setACL().withACL(CONFIG.getAcls()); connectionStateListener = getConnectionStateListener(); curaFramework.getConnectionStateListenable() .addListener(connectionStateListener); unhandledErrorListener = getUnhandledErrorListener(); curaFramework.getUnhandledErrorListenable() .addListener(unhandledErrorListener); cache = new PathChildrenCache(curaFramework, CONFIG.getParentPath(), true); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); closeAbles.add(cache); closeAbles.add(curaFramework); } }
private void init(){ client = CuratorFrameworkFactory.newClient(zooKeeperUrl, new RetryForever(1000)); client.start(); treeCache.getListenable().addListener(new TreeCacheListener() { @Override public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
/** * connect ZK, register watchers */ public CuratorFramework mkClient(Map conf, List<String> servers, Object port, String root, final WatcherCallBack watcher) { CuratorFramework fk = Utils.newCurator(conf, servers, port, root); fk.getCuratorListenable().addListener(new CuratorListener() { @Override public void eventReceived(CuratorFramework _fk, CuratorEvent e) throws Exception { if (e.getType().equals(CuratorEventType.WATCHED)) { WatchedEvent event = e.getWatchedEvent(); watcher.execute(event.getState(), event.getType(), event.getPath()); } } }); fk.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() { @Override public void unhandledError(String msg, Throwable error) { String errmsg = "Unrecoverable zookeeper error, halting process: " + msg; LOG.error(errmsg, error); JStormUtils.halt_process(1, "Unrecoverable zookeeper error"); } }); fk.start(); return fk; }
/** * 注册连接状态监听器. * * @param listener 连接状态监听器 */ public void addConnectionStateListener(final ConnectionStateListener listener) { getClient().getConnectionStateListenable().addListener(listener); }
curator.getCuratorListenable().addListener(localListener); listener.set(localListener); curator.checkExists().inBackground(callback).forPath("/foo");
@Override public void close() throws IOException { State currentState = state.getAndSet(State.CLOSED); if (currentState == State.CLOSED || currentState == State.LATENT) return; client.getConnectionStateListenable().removeListener(connectionStateListener); String localNodePath = nodePath.getAndSet(null); if (localNodePath == null) return; try { client.delete().guaranteed().forPath(localNodePath); } catch (KeeperException.NoNodeException ignore) { } catch (Exception e) { LOG.error("Deleting node: " + localNodePath, e); throw new IOException(e); } }
@Override public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.CONNECTED) { initialConnection.countDown(); client.getConnectionStateListenable().removeListener(this); } }
public CuratorFramework makeCurator(CuratorConfig config, EnsembleProvider ensembleProvider, Lifecycle lifecycle) final Builder builder = CuratorFrameworkFactory.builder(); if (!Strings.isNullOrEmpty(config.getZkUser()) && !Strings.isNullOrEmpty(config.getZkPwd())) { builder.authorization( .build(); framework.getUnhandledErrorListenable().addListener((message, e) -> { log.error(e, "Unhandled error in Curator Framework"); try {