本文整理匯總了Java中org.apache.zookeeper.Watcher類的典型用法代碼示例。如果您正苦於以下問題:Java Watcher類的具體用法?Java Watcher怎麽用?Java Watcher使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Watcher類屬於org.apache.zookeeper包,在下文中一共展示了Watcher類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: setUp
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
zookeeper = new ZooKeeper("127.0.0.1:2181", 10000, event -> {
if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
System.out.println("Zookeeper connected.");
} else {
throw new RuntimeException("Error connecting to zookeeper");
}
latch.countDown();
});
latch.await();
CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));
curatorFramework.start();
AsyncCuratorFramework asyncCuratorFramework = AsyncCuratorFramework.wrap(curatorFramework);
logInfoStorage = new LogInfoStorageImpl(asyncCuratorFramework);
}
示例2: watchNode
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
private void watchNode(final ZooKeeper zk) {
try {
List<String> nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeChildrenChanged) {
watchNode(zk);
}
}
});
List<String> dataList = new ArrayList<>();
for (String node : nodeList) {
byte[] bytes = zk.getData(Constant.ZK_REGISTRY_PATH + "/" + node, false, null);
dataList.add(new String(bytes));
}
LOGGER.debug("node data: {}", dataList);
this.dataList = dataList;
LOGGER.debug("Service discovery triggered updating connected server node.");
updateConnectedServer();
} catch (Exception e) {
LOGGER.error("", e);
}
}
示例3: connect
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
private void connect(TxZookeeperConfig config) {
try {
zooKeeper = new ZooKeeper(config.getHost(), config.getSessionTimeOut(), watchedEvent -> {
if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
// 放開閘門, wait在connect方法上的線程將被喚醒
COUNT_DOWN_LATCH.countDown();
}
});
COUNT_DOWN_LATCH.await();
Stat stat = zooKeeper.exists(rootPath, false);
if (stat == null) {
zooKeeper.create(rootPath, rootPath.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} catch (Exception e) {
throw new TransactionIoException(e);
}
}
開發者ID:yu199195,項目名稱:happylifeplat-transaction,代碼行數:20,代碼來源:ZookeeperTransactionRecoverRepository.java
示例4: process
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
@Override
public void process(WatchedEvent event) throws Exception {
String topicPath = zkConf.getZKBasePath() + "/topics/" + topic;
LOG.info("get zookeeper notification for path={}", topicPath);
if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
List<String> newQueues = zkClient.getChildren().forPath(topicPath);
List<Integer> newQueueIds = new ArrayList<>();
for (String queue : newQueues) {
newQueueIds.add(Integer.valueOf(queue));
}
List<Integer> oldQueueIds = metadata.getTopicQueues(topic);
Collection<Integer> addedQueueIds = CollectionUtils.subtract(newQueueIds, oldQueueIds);
Collection<Integer> deletedQueueIds = CollectionUtils.subtract(oldQueueIds, newQueueIds);
for (Integer queueId : addedQueueIds) {
String queuePath = topicPath + "/" + queueId;
String queueData = new String(zkClient.getData().forPath(queuePath));
Integer shardingId = Integer.valueOf(queueData);
metadata.addTopicQueue(topic, queueId, shardingId);
}
metadata.deleteTopicQueue(topic, deletedQueueIds);
}
zkClient.getChildren()
.usingWatcher(new TopicWatcher(topic))
.forPath(topicPath);
}
示例5: getZooKeeperConnection
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
/**
* 獲取Zookeeper連接
* @return
*/
public static ZooKeeper getZooKeeperConnection() {
try {
// Zookeeper連接閉鎖cdl
final CountDownLatch cdl = new CountDownLatch(1);
final ZooKeeper zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
// 當連接成功時放開cdl
cdl.countDown();
}
}
});
// cdl阻塞
cdl.await();
return zooKeeper;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
示例6: processResult
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
public void processResult(int rc, String path,
Object ctx, byte[] data, Stat stat) {
if (rc == KeeperException.Code.NONODE.intValue()) {
// we can just ignore because the child watcher takes care of this
return;
}
if (rc != KeeperException.Code.OK.intValue()) {
zk.getData(myNode, (Watcher)ctx, this, ctx);
}
int currVer = stat.getVersion();
if (currVer != lastVer) {
String parts[] = new String(data).split(" ", 2);
myInstance.configure(parts[1]);
lastVer = currVer;
}
}
示例7: init
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
/**
* 連接zookeeper
*
* @author gaoxianglong
*/
public void init() {
try {
zkClient = new ZooKeeper(zkAddress, zkSessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
KeeperState state = event.getState();
switch (state) {
case SyncConnected:
countDownLatch.countDown();
logger.info("connection zookeeper success");
break;
case Disconnected:
logger.warn("zookeeper connection is disconnected");
break;
case Expired:
logger.error("zookeeper session expired");
break;
case AuthFailed:
logger.error("authentication failure");
break;
default:
break;
}
}
});
countDownLatch.await();
} catch (Exception e) {
logger.error("error", e);
}
}
示例8: updateZnodeData
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
private void updateZnodeData(Stat stat, Watcher watcher) {
if (isDestroyed()) {
return;
}
Znode znode = getData();
ZooKeeperConnection zooKeeperConnection = getZooKeeperConnection();
String path = znode.getPath();
byte[] data;
try {
if (watcher != null) {
data = zooKeeperConnection.getData(path, watcher, stat);
}
else {
data = zooKeeperConnection.getData(path, false, stat);
}
znode.setData(data);
znode.setDataReadable(true);
}
catch (Exception e) {
znode.setDataReadable(false);
}
}
示例9: addWatch
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
public synchronized void addWatch(String path, Watcher watcher) {
HashSet<Watcher> list = watchTable.get(path);
if (list == null) {
// don't waste memory if there are few watches on a node
// rehash when the 4th entry is added, doubling size thereafter
// seems like a good compromise
list = new HashSet<Watcher>(4);
watchTable.put(path, list);
}
list.add(watcher);
HashSet<String> paths = watch2Paths.get(watcher);
if (paths == null) {
// cnxns typically have many watches, so use default cap here
paths = new HashSet<String>();
watch2Paths.put(watcher, paths);
}
paths.add(path);
}
示例10: processWatchEvent
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
@Override
public synchronized void processWatchEvent(ZooKeeper zk,
WatchedEvent event) throws Exception {
if (forExpire) {
// a hack... couldn't find a way to trigger expired event.
WatchedEvent expriredEvent = new WatchedEvent(
Watcher.Event.EventType.None,
Watcher.Event.KeeperState.Expired, null);
super.processWatchEvent(zk, expriredEvent);
forExpire = false;
syncBarrier.await();
} else {
super.processWatchEvent(zk, event);
}
}
示例11: getChildren
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
public List<String> getChildren(String path, Stat stat, Watcher watcher)
throws KeeperException.NoNodeException {
DataNode n = nodes.get(path);
if (n == null) {
throw new KeeperException.NoNodeException();
}
synchronized (n) {
if (stat != null) {
n.copyStat(stat);
}
ArrayList<String> children;
Set<String> childs = n.getChildren();
if (childs != null) {
children = new ArrayList<String>(childs.size());
children.addAll(childs);
} else {
children = new ArrayList<String>(0);
}
if (watcher != null) {
childWatches.addWatch(path, watcher);
}
return children;
}
}
示例12: testRootWatchTriggered
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
@Test(timeout = 60000)
public void testRootWatchTriggered() throws Exception {
class MyWatcher implements Watcher{
boolean fired=false;
public void process(WatchedEvent event) {
if(event.getPath().equals("/"))
fired=true;
}
}
MyWatcher watcher=new MyWatcher();
// set a watch on the root node
dt.getChildren("/", new Stat(), watcher);
// add a new node, should trigger a watch
dt.createNode("/xyz", new byte[0], null, 0, dt.getNode("/").stat.getCversion()+1, 1, 1);
Assert.assertFalse("Root node watch not triggered",!watcher.fired);
}
示例13: connectZooKeeper
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
private static ZooKeeper connectZooKeeper(String ensemble)
throws IOException, KeeperException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
ZooKeeper zkc = new ZooKeeper(HOSTPORT, 3600, new Watcher() {
public void process(WatchedEvent event) {
if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
if (!latch.await(10, TimeUnit.SECONDS)) {
throw new IOException("Zookeeper took too long to connect");
}
return zkc;
}
示例14: getStatus
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
/**
* Gets the status of a node in ZooKeeper
*
* @param p_path
* the node path
* @param p_watcher
* the watcher
* @return true if the node exists, fals eotherwise
* @throws ZooKeeperException
* if ZooKeeper could not accessed
*/
public Stat getStatus(final String p_path, final Watcher p_watcher) throws ZooKeeperException {
Stat ret;
assert p_path != null;
try {
if (m_zookeeper == null) {
connect();
}
if (!p_path.isEmpty()) {
ret = m_zookeeper.exists(m_path + '/' + p_path, p_watcher);
} else {
ret = m_zookeeper.exists(m_path, p_watcher);
}
} catch (final KeeperException | InterruptedException e) {
throw new ZooKeeperException("Could not access ZooKeeper", e);
}
return ret;
}
示例15: ZookeeperRegistry
import org.apache.zookeeper.Watcher; //導入依賴的package包/類
public ZookeeperRegistry(URL url, ZkClient zkClient) {
super(url);
this.zkClient = zkClient;
IZkStateListener zkStateListener = new IZkStateListener() {
@Override
public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {
// do nothing
}
@Override
public void handleNewSession() throws Exception {
logger.info("zkRegistry get new session notify.");
}
@Override
public void handleSessionEstablishmentError(Throwable throwable) throws Exception {
}
};
this.zkClient.subscribeStateChanges(zkStateListener);
}