类org.apache.zookeeper.Watcher.Event.KeeperState源码实例Demo

下面列出了怎么用org.apache.zookeeper.Watcher.Event.KeeperState的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: dubbo-2.6.5   文件: ZkclientZookeeperClient.java
public ZkclientZookeeperClient(URL url) {
    super(url);
    client = new ZkClientWrapper(url.getBackupAddress(), 30000);
    client.addListener(new IZkStateListener() {
        @Override
        public void handleStateChanged(KeeperState state) throws Exception {
            ZkclientZookeeperClient.this.state = state;
            if (state == KeeperState.Disconnected) {
                stateChanged(StateListener.DISCONNECTED);
            } else if (state == KeeperState.SyncConnected) {
                stateChanged(StateListener.CONNECTED);
            }
        }

        @Override
        public void handleNewSession() throws Exception {
            stateChanged(StateListener.RECONNECTED);
        }
    });
    client.start();
}
 
源代码2 项目: distributedlog   文件: TestZooKeeperClient.java
private void expireZooKeeperSession(ZooKeeper zk, int timeout)
        throws IOException, InterruptedException, KeeperException {
    final CountDownLatch latch = new CountDownLatch(1);

    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected) {
                latch.countDown();
            }
        }},
        zk.getSessionId(),
        zk.getSessionPasswd());

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }

    newZk.close();
}
 
源代码3 项目: helix   文件: ZkClient.java
public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit)
    throws ZkInterruptedException {
  validateCurrentThread();
  Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time));

  LOG.debug("Waiting for keeper state " + keeperState);
  acquireEventLock();
  try {
    boolean stillWaiting = true;
    while (_currentState != keeperState) {
      if (!stillWaiting) {
        return false;
      }
      stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout);
    }
    LOG.debug("State is " + (_currentState == null ? "CLOSED" : _currentState));
    return true;
  } catch (InterruptedException e) {
    throw new ZkInterruptedException(e);
  } finally {
    getEventLock().unlock();
  }
}
 
源代码4 项目: pinpoint   文件: FlinkServerRegister.java
@SuppressWarnings("deprecation")
@Override
public void process(WatchedEvent event) {
    logger.info("Handle Zookeeper Event({}) started.", event);

    KeeperState state = event.getState();
    EventType eventType = event.getType();
    String path = event.getPath();

    if (state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) {
        // when this happens, ephemeral node disappears
        // reconnects automatically, and process gets notified for all events
        if (eventType == EventType.NodeChildrenChanged) {
            logger.info("zookeeper Event occurs : NodeChildrenChanged event");
        } else if (eventType == EventType.NodeDeleted) {
            logger.info("zookeeper Event occurs : NodeDeleted");
        } else if (eventType == EventType.NodeDataChanged) {
            logger.info("zookeeper Event occurs : NodeDataChanged");
        }
    }
    logger.info("Handle Zookeeper Event({}) completed.", event);
}
 
源代码5 项目: light-task-scheduler   文件: ZkClientZkClient.java
public ZkClientZkClient(Config config) {
    String registryAddress = NodeRegistryUtils.getRealRegistryAddress(config.getRegistryAddress());
    zkClient = new ZkClient(registryAddress, connectionTimeout);

    zkClient.subscribeStateChanges(new IZkStateListener() {

        public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {
            ZkClientZkClient.this.state = state;
            if (state == KeeperState.Disconnected) {
                stateChanged(StateListener.DISCONNECTED);
            } else if (state == KeeperState.SyncConnected) {
                stateChanged(StateListener.CONNECTED);
            } else if (state == KeeperState.Expired) {
                stateChanged(StateListener.DISCONNECTED);
            }
        }

        public void handleNewSession() throws Exception {
            stateChanged(StateListener.RECONNECTED);
        }
    });
}
 
源代码6 项目: dubbox   文件: ZkclientZookeeperClient.java
public ZkclientZookeeperClient(URL url) {
	super(url);
	client = new ZkClient(
               url.getBackupAddress(),
               url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT),
               url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT));
	client.subscribeStateChanges(new IZkStateListener() {
		public void handleStateChanged(KeeperState state) throws Exception {
			ZkclientZookeeperClient.this.state = state;
			if (state == KeeperState.Disconnected) {
				stateChanged(StateListener.DISCONNECTED);
			} else if (state == KeeperState.SyncConnected) {
				stateChanged(StateListener.CONNECTED);
			}
		}
		public void handleNewSession() throws Exception {
			stateChanged(StateListener.RECONNECTED);
		}
	});
}
 
源代码7 项目: TakinRPC   文件: ZkClient.java
public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException {
    if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
        throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
    }
    Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time));

    logger.debug("Waiting for keeper state " + keeperState);
    acquireEventLock();
    try {
        boolean stillWaiting = true;
        while (_currentState != keeperState) {
            if (!stillWaiting) {
                return false;
            }
            stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout);
        }
        logger.debug("State is " + _currentState);
        return true;
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
}
 
源代码8 项目: elephant   文件: ZkClientRegisterCenter.java
@Override
public void init() {
	this.zkClient = new ZkClient(this.zkAddress, this.zkSessionTimeOut, this.zkConnectionTimeOut, new SerializableSerializer());
	initRootPath();
	this.zkClient.subscribeStateChanges(new IZkStateListener() {
		@Override
		public void handleStateChanged(KeeperState state) throws Exception {
			if(zkReconnectionListener != null && state.name().equals(KeeperState.SyncConnected.name())){
				zkReconnectionListener.handleStateForSyncConnected();
			}
		}
		@Override
		public void handleSessionEstablishmentError(Throwable error)throws Exception {
			log.error("处理会话建立错误:{}",error);
		}
		@Override
		public void handleNewSession() throws Exception {
			log.info("会话建立成功!");
		}
	});
}
 
源代码9 项目: JobX   文件: ZkclientZookeeperClient.java
public ZkclientZookeeperClient(URL url) {
    super(url);
    client = new ZkClient(url.getBackupAddress(), Constants.ZK_CONNECTION_TIMEOUT);
    client.subscribeStateChanges(new IZkStateListener() {
        public void handleStateChanged(KeeperState state) throws Exception {
            ZkclientZookeeperClient.this.state = state;
            if (state == KeeperState.Disconnected) {
                stateChanged(StateListener.DISCONNECTED);
            } else if (state == KeeperState.SyncConnected) {
                stateChanged(StateListener.CONNECTED);
            }
        }

        public void handleNewSession() throws Exception {
            stateChanged(StateListener.RECONNECTED);
        }

        @Override
        public void handleSessionEstablishmentError(Throwable throwable) throws Exception {

        }
    });
}
 
源代码10 项目: dremio-oss   文件: ZkDistributedSemaphore.java
private void onEvent(WatchedEvent event) {

    if(event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
      Collection<UpdateListener> col = new ArrayList<>(listeners.keySet());
      for(UpdateListener l : col) {
        l.updated();
      }
    } else if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected){
      // re set the watcher after a disconnect.
      try {
        setWatcher();
      } catch (Exception e) {
        logger.error("Failure while re-setting watcher after reconnect.", e);
      }
    }
  }
 
源代码11 项目: distributedlog   文件: TestZooKeeperClient.java
/**
 * {@link https://issues.apache.org/jira/browse/DL-34}
 */
@DistributedLogAnnotations.FlakyTest
@Ignore
@Test(timeout = 60000)
public void testAclAuthSpansExpiration() throws Exception {
    ZooKeeperClient zkcAuth = buildAuthdClient("test");
    zkcAuth.get().create("/test", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);

    CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth);
    CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth);

    expireZooKeeperSession(zkcAuth.get(), 2000);

    expired.await(2, TimeUnit.SECONDS);
    connected.await(2, TimeUnit.SECONDS);

    zkcAuth.get().create("/test/key1", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);

    rmAll(zkcAuth, "/test");
}
 
源代码12 项目: distributedlog   文件: TestZooKeeperClient.java
/**
 * {@link https://issues.apache.org/jira/browse/DL-34}
 */
@DistributedLogAnnotations.FlakyTest
@Ignore
@Test(timeout = 60000)
public void testAclAuthSpansExpirationNonRetryableClient() throws Exception {
    ZooKeeperClient zkcAuth = clientBuilder().retryPolicy(null).zkAclId("test").build();
    zkcAuth.get().create("/test", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);

    CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth);
    CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth);

    expireZooKeeperSession(zkcAuth.get(), 2000);

    expired.await(2, TimeUnit.SECONDS);
    connected.await(2, TimeUnit.SECONDS);

    zkcAuth.get().create("/test/key1", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);

    rmAll(zkcAuth, "/test");
}
 
源代码13 项目: distributedlog   文件: TestZooKeeperClient.java
/**
 * {@link https://issues.apache.org/jira/browse/DL-34}.
 */
@DistributedLogAnnotations.FlakyTest
@Ignore
@Test(timeout = 60000)
public void testAclAuthSpansExpiration() throws Exception {
    ZooKeeperClient zkcAuth = buildAuthdClient("test");
    zkcAuth.get().create("/test", new byte[0],
            DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);

    CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth);
    CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth);

    expireZooKeeperSession(zkcAuth.get(), 2000);

    expired.await(2, TimeUnit.SECONDS);
    connected.await(2, TimeUnit.SECONDS);

    zkcAuth.get().create("/test/key1", new byte[0],
            DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);

    rmAll(zkcAuth, "/test");
}
 
源代码14 项目: distributedlog   文件: TestZooKeeperClient.java
/**
 * {@link https://issues.apache.org/jira/browse/DL-34}.
 */
@DistributedLogAnnotations.FlakyTest
@Ignore
@Test(timeout = 60000)
public void testAclAuthSpansExpirationNonRetryableClient() throws Exception {
    ZooKeeperClient zkcAuth = clientBuilder().retryPolicy(null).zkAclId("test").build();
    zkcAuth.get().create("/test", new byte[0],
            DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);

    CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth);
    CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth);

    expireZooKeeperSession(zkcAuth.get(), 2000);

    expired.await(2, TimeUnit.SECONDS);
    connected.await(2, TimeUnit.SECONDS);

    zkcAuth.get().create("/test/key1", new byte[0],
            DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT);

    rmAll(zkcAuth, "/test");
}
 
源代码15 项目: zkclient   文件: ZKConnectionImpl.java
/**
 * 等待直到连接处于某个状态才停止,如果超时返回false,当正确处于某个状态返回true
 * 这里使用到了EventLock的 stateChangedCondition 条件,
 * 如果当前状态不是期待的状态,则此时线程处于等待状态。
 * 1.如果事件监听器发现ZooKeeper状态改变,则会标记stateChangedCondition,当前线程被唤醒,
 *         当前线程继续判断是否是期待的状态,如果是则返回true,如果不是,则线程继续处于等待状态,直到下次ZooKeeper状态改变,重复上述操作。
 * 2.如果等待超时则直接返回false。
 * @param keeperState ZooKeeper状态
 * @param timeout 超时时间 
 * @param timeUnit 时间单位
 * @return
 * @throws ZKInterruptedException  
 * @return boolean
 */
private boolean waitForKeeperState(KeeperState keeperState, long timeout, TimeUnit timeUnit) throws ZKInterruptedException {
    Date timeoutDate = new Date(System.currentTimeMillis() + timeUnit.toMillis(timeout));
    
    LOG.info("Waiting for ZooKeeper state " + keeperState);
    //使用可中断锁
    acquireEventLockInterruptibly();
    try {
        boolean stillWaiting = true;
        while (currentState != keeperState) {
            if (!stillWaiting) {
                return false;
            }
            stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeoutDate);
            if (currentState == KeeperState.AuthFailed && isZkSaslEnabled) {
                throw new ZKException("authorization failed");
            }
        }
        LOG.info("ZooKeeper State is " + currentState);
        return true;
    } catch (InterruptedException e) {
        throw new ZKInterruptedException(e);
    } finally {
       releaseEventLock();
    }
}
 
源代码16 项目: Mario   文件: ZooKeeperClient.java
@Override
public void process(WatchedEvent event) {
    logger.info("SessionWatcher: " + connectionString + "|"
                + event.getType() + "|" + event.getState());
    if (event.getType() == EventType.None) {
        if (event.getState().equals(KeeperState.SyncConnected)) {
            isAvailable = true;
            countDownLatch.countDown();
        } else if (event.getState().equals(KeeperState.Expired)) {
            createConnection();
        } else if (event.getState().equals(KeeperState.Disconnected)) {
            isAvailable = false;
        }
    }
}
 
源代码17 项目: DDMQ   文件: ZkClient.java
public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException {
    if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) {
        throw new IllegalArgumentException("Must not be done in the zookeeper event thread.");
    }
    Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time));

    LOG.info("Waiting for keeper state " + keeperState);
    acquireEventLock();
    try {
        boolean stillWaiting = true;
        while (_currentState != keeperState) {
            if (!stillWaiting) {
                return false;
            }
            stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout);
            // Throw an exception in the case authorization fails
            if (_currentState == KeeperState.AuthFailed && _isZkSaslEnabled) {
                throw new ZkAuthFailedException("Authentication failure");
            }
        }
        LOG.debug("State is " + _currentState);
        return true;
    } catch (InterruptedException e) {
        throw new ZkInterruptedException(e);
    } finally {
        getEventLock().unlock();
    }
}
 
源代码18 项目: DDMQ   文件: ZkClient.java
public void setCurrentState(KeeperState currentState) {
    getEventLock().lock();
    try {
        _currentState = currentState;
    } finally {
        getEventLock().unlock();
    }
}
 
源代码19 项目: uncode-schedule   文件: ZKManager.java
private void sessionEvent(CountDownLatch connectionLatch, WatchedEvent event) {
  if (event.getState() == KeeperState.SyncConnected) {
    LOG.info("收到ZK连接成功事件!");
    connectionLatch.countDown();
  } else if (event.getState() == KeeperState.Expired) {
    LOG.error("会话超时,等待重新建立ZK连接...");
    try {
      reConnection();
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);
    }
  } // Disconnected:Zookeeper会自动处理Disconnected状态重连
}
 
源代码20 项目: helix   文件: ZkTestHelper.java
/**
 * Simulate a zk state change by calling {@link ZkClient#process(WatchedEvent)} directly
 */
public static void simulateZkStateReconnected(RealmAwareZkClient client) {
  ZkClient zkClient = (ZkClient) client;
  WatchedEvent event = new WatchedEvent(EventType.None, KeeperState.Disconnected, null);
  zkClient.process(event);
  event = new WatchedEvent(EventType.None, KeeperState.SyncConnected, null);
  zkClient.process(event);
}
 
源代码21 项目: spring-zk-test   文件: ConnectionZk.java
/**
 * 连接zookeeper
 * 
 * @author JohnGao
 */
private void connection() {
	try {
		zk_client = new ZooKeeper(zk_address, session_timeout,
				new Watcher() {
					@Override
					public void process(WatchedEvent event) {
						final KeeperState STATE = event.getState();
						switch (STATE) {
						case SyncConnected:
							countDownLatch.countDown();
							logger.info("成功连接zookeeper服务器");
							break;
						case Disconnected:
							logger.warn("与zookeeper服务器断开连接");
							break;
						case Expired:
							logger.error("session会话失效...");
							break;
						default:
							break;
						}
					}
				});
		countDownLatch.await();
		/* 注册与UserinfoBean相关的节点 */
		registerUserNode.register(zk_client, usernamePath, passwordPath);
		/* 注册与IdinfoBean相关的节点 */
		registerIdNode.register(zk_client, id);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
源代码22 项目: pulsar   文件: ZooKeeperSessionWatcherTest.java
@Test
public void testRun6() throws Exception {
    sessionWatcher.run();
    assertFalse(sessionWatcher.isShutdownStarted());
    assertEquals(sessionWatcher.getKeeperState(), KeeperState.SyncConnected);
    assertEquals(shutdownService.getExitCode(), 0);
}
 
源代码23 项目: disconf   文件: ConnectionWatcher.java
/**
 * 当连接成功时调用的
 */
@Override
public void process(WatchedEvent event) {
    if (event.getState() == KeeperState.SyncConnected) {

        LOGGER.info("zk SyncConnected");
        connectedSignal.countDown();

    } else if (event.getState().equals(KeeperState.Disconnected)) {

        // 这时收到断开连接的消息,这里其实无能为力,因为这时已经和ZK断开连接了,只能等ZK再次开启了
        LOGGER.warn("zk Disconnected");

    } else if (event.getState().equals(KeeperState.Expired)) {

        if (!debug) {

            // 这时收到这个信息,表示,ZK已经重新连接上了,但是会话丢失了,这时需要重新建立会话。
            LOGGER.error("zk Expired");

            // just reconnect forever
            reconnect();
        } else {
            LOGGER.info("zk Expired");
        }

    } else if (event.getState().equals(KeeperState.AuthFailed)) {

        LOGGER.error("zk AuthFailed");
    }
}
 
源代码24 项目: pulsar   文件: ZooKeeperSessionWatcherTest.java
@Test
public void testRun4() throws Exception {
    sessionWatcher.run();
    assertFalse(sessionWatcher.isShutdownStarted());
    assertEquals(sessionWatcher.getKeeperState(), KeeperState.SyncConnected);
    assertEquals(shutdownService.getExitCode(), 0);
}
 
源代码25 项目: jstorm   文件: DistributedClusterState.java
public DistributedClusterState(Map<Object, Object> conf) throws Exception {
    this.conf = conf;

    // just mkdir STORM_ZOOKEEPER_ROOT dir
    CuratorFramework _zk = mkZk();
    String path = String.valueOf(this.conf.get(Config.STORM_ZOOKEEPER_ROOT));
    zkObj.mkdirs(_zk, path);
    _zk.close();

    active = new AtomicBoolean(true);

    watcher = new WatcherCallBack() {
        @Override
        public void execute(KeeperState state, EventType type, String path) {
            if (active.get()) {
                if (!(state.equals(KeeperState.SyncConnected))) {
                    LOG.warn("Received event " + state + ":" + type + ":" + path + " with disconnected Zookeeper.");
                } else {
                    LOG.info("Received event " + state + ":" + type + ":" + path);
                }

                if (!type.equals(EventType.None)) {
                    for (Entry<UUID, ClusterStateCallback> e : callbacks.entrySet()) {
                        ClusterStateCallback fn = e.getValue();
                        fn.execute(type, path);
                    }
                }
            }
        }
    };
    zk = null;
    zk = mkZk(watcher);

}
 
源代码26 项目: Mario   文件: ZooKeeperClientTest.java
@Override
public void process(WatchedEvent event) {
	System.err.println("MyWatcher " + event.getType() + " | "
			+ event.getState());
	if (event.getType() == EventType.None) {
		if (event.getState().equals(KeeperState.SyncConnected)) {
			coutCountDownLatch.countDown();
		}
	}
}
 
源代码27 项目: pulsar   文件: ZooKeeperSessionWatcherTest.java
@Test
public void testRun3() throws Exception {
    zkClient.shutdown();
    sessionWatcher.run();
    assertFalse(sessionWatcher.isShutdownStarted());
    assertEquals(sessionWatcher.getKeeperState(), KeeperState.Disconnected);
    assertEquals(shutdownService.getExitCode(), 0);
}
 
源代码28 项目: recsys-offline   文件: SwiftWatcher.java
@Override
public void process(WatchedEvent event) {
	if (event.getState() == KeeperState.SyncConnected) {
		conSignal.countDown();
	}
	synchronized (this) {
		if (event.getPath() != null
				&& event.getPath().equals(Constants.zk_start_flag)
				&& event.getType() == Event.EventType.NodeCreated) {
			try {
				if (zk.exists(Constants.zk_znode, false) != null) {
					List<String> list = zk.getChildren(Constants.zk_znode,	true);
					if (list != null && list.size() > 0) {
						for (String str : list) {
							zk.delete(Constants.zk_znode + "/" + str, -1);
						}
					}
					zk.delete(Constants.zk_znode, -1);
					logger.info("delete zookeeper dir successful. It begin to start hadoop task...");
					Recsys.runAllTask();
					
				} 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
 
源代码29 项目: TakinRPC   文件: ZkClient.java
private void fireStateChangedEvent(final KeeperState state) {
    for (final IZkStateListener stateListener : _stateListener) {
        _eventThread.send(new ZkEvent("State changed to " + state + " sent to " + stateListener) {

            @Override
            public void run() throws Exception {
                stateListener.handleStateChanged(state);
            }
        });
    }
}
 
源代码30 项目: TakinRPC   文件: ZkClient.java
public void setCurrentState(KeeperState currentState) {
    getEventLock().lock();
    try {
        _currentState = currentState;
    } finally {
        getEventLock().unlock();
    }
}
 
 类所在包
 同包方法