当前位置: 首页>>代码示例>>Java>>正文


Java Watcher类代码示例

本文整理汇总了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);
}
 
开发者ID:aCoder2013,项目名称:fastmq,代码行数:18,代码来源:LogStorageImplTest.java

示例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);
    }
}
 
开发者ID:islittlechen,项目名称:lionrpc,代码行数:25,代码来源:ServiceDiscovery.java

示例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);
}
 
开发者ID:wenweihu86,项目名称:distmq,代码行数:26,代码来源:MetadataManager.java

示例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;
    }
}
 
开发者ID:jthinking,项目名称:linux-memory-monitor,代码行数:26,代码来源:ServerMonitor.java

示例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;
    }
}
 
开发者ID:l294265421,项目名称:ZooKeeper,代码行数:17,代码来源:InstanceContainer.java

示例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);
	}
}
 
开发者ID:yunjiweidian,项目名称:TITAN,代码行数:36,代码来源:ZookeeperConnManager.java

示例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);
        }
    }
 
开发者ID:baloise,项目名称:eZooKeeper,代码行数:27,代码来源:ZnodeModel.java

示例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);
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:20,代码来源:WatchManager.java

示例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);
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:17,代码来源:TestZKRMStateStoreZKClientConnections.java

示例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;
    }
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:26,代码来源:DataTree.java

示例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);
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:17,代码来源:DataTreeTest.java

示例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;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:17,代码来源:TestCurrentInprogress.java

示例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;
}
 
开发者ID:hhu-bsinfo,项目名称:dxram,代码行数:33,代码来源:ZooKeeperHandler.java

示例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);
}
 
开发者ID:TFdream,项目名称:mango,代码行数:23,代码来源:ZookeeperRegistry.java


注:本文中的org.apache.zookeeper.Watcher类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。