本文整理汇总了Java中org.apache.zookeeper.ZooKeeper类的典型用法代码示例。如果您正苦于以下问题:Java ZooKeeper类的具体用法?Java ZooKeeper怎么用?Java ZooKeeper使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ZooKeeper类属于org.apache.zookeeper包,在下文中一共展示了ZooKeeper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testInvalidSaslIds
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
@Test
public void testInvalidSaslIds() throws Exception {
ZooKeeper zk = createClient();
List<String> invalidIds = new ArrayList<String>();
invalidIds.add("[email protected]/server.com");
invalidIds.add("[email protected]@KERB.REALM2");
int i = 0;
for(String invalidId: invalidIds) {
List<ACL> aclList = new ArrayList<ACL>();
try {
ACL acl = new ACL(0,new Id("sasl",invalidId));
aclList.add(acl);
zk.create("/invalid"+i,null,aclList,CreateMode.PERSISTENT);
Assert.fail("SASLAuthenticationProvider.isValid() failed to catch invalid Id.");
}
catch (KeeperException.InvalidACLException e) {
// ok.
}
finally {
i++;
}
}
}
示例2: getConnectedZkClient
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
private ZooKeeper getConnectedZkClient() throws IOException {
ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this);
long start = System.currentTimeMillis();
while (!connected) {
long end = System.currentTimeMillis();
if (end - start > 5000) {
Assert.assertTrue("Could not connect with server in 5 seconds",
false);
}
try {
Thread.sleep(200);
} catch (Exception e) {
LOG.warn("Interrupted");
}
}
return zk;
}
示例3: run
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
public void run() {
byte b[] = new byte[256];
try {
for (; current < count; current++) {
ZooKeeper zk = parent.createClient();
try {
zk.create(prefix + current, b, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} finally {
try {
zk.close();
} catch (InterruptedException e) {
LOG.warn("Unexpected", e);
}
}
}
} catch (Throwable t) {
LOG.error("Client create operation Assert.failed", t);
}
}
示例4: getNewZooKeeper
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
/**
* Get a new zookeeper client instance. protected so that test class can
* inherit and pass in a mock object for zookeeper
*
* @return new zookeeper client instance
* @throws IOException
* @throws KeeperException zookeeper connectionloss exception
*/
protected synchronized ZooKeeper getNewZooKeeper() throws IOException,
KeeperException {
// Unfortunately, the ZooKeeper constructor connects to ZooKeeper and
// may trigger the Connected event immediately. So, if we register the
// watcher after constructing ZooKeeper, we may miss that event. Instead,
// we construct the watcher first, and have it block any events it receives
// before we can set its ZooKeeper reference.
watcher = new WatcherWithClientRef();
ZooKeeper zk = new ZooKeeper(zkHostPort, zkSessionTimeout, watcher);
watcher.setZooKeeperRef(zk);
// Wait for the asynchronous success/failure. This may throw an exception
// if we don't connect within the session timeout.
watcher.waitForZKConnectionEvent(zkSessionTimeout);
for (ZKAuthInfo auth : zkAuthInfo) {
zk.addAuthInfo(auth.getScheme(), auth.getAuth());
}
return zk;
}
示例5: testSuperIsSuper
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
@Test
public void testSuperIsSuper() throws Exception {
ZooKeeper zk = createClient();
try {
zk.create("/digest_read", null, Arrays.asList(new ACL(Perms.READ, otherDigestUser)), CreateMode.PERSISTENT);
zk.create("/digest_read/sub", null, Arrays.asList(new ACL(Perms.READ, otherDigestUser)), CreateMode.PERSISTENT);
zk.create("/sasl_read", null, Arrays.asList(new ACL(Perms.READ, otherSaslUser)), CreateMode.PERSISTENT);
zk.create("/sasl_read/sub", null, Arrays.asList(new ACL(Perms.READ, otherSaslUser)), CreateMode.PERSISTENT);
zk.delete("/digest_read/sub", -1);
zk.delete("/digest_read", -1);
zk.delete("/sasl_read/sub", -1);
zk.delete("/sasl_read", -1);
//If the test failes it will most likely fail with a NoAuth exception before it ever gets to this assertion
Assert.assertEquals(authFailed.get(), 0);
} finally {
zk.close();
}
}
示例6: init
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
/**
* 建立zk连接,并初始化root和config节点
*/
private void init() {
loadLocalProperties();
try {
this.zooKeeper = new ZooKeeper(address, 1000000, new DefaultDataWatcher());
Stat stat = this.zooKeeper.exists(PathVarConst.ROOT_PATH, null);
if (stat == null) {
this.zooKeeper.create(PathVarConst.ROOT_PATH, "root".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
this.zooKeeper.create(PathVarConst.ROOTCONF_PATH, "config".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
} catch (Exception e) {
LOGGER.error("zookeeper连接配置出错,请检查配置文件", e);
}
}
示例7: verifyUnexpectedBeans
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
private void verifyUnexpectedBeans(Set<ObjectName> children) {
if (allClients != null) {
for (ZooKeeper zkc : allClients) {
Iterator<ObjectName> childItr = children.iterator();
while (childItr.hasNext()) {
ObjectName clientBean = childItr.next();
if (clientBean.toString().contains(
getHexSessionId(zkc.getSessionId()))) {
LOG.info("found name:" + zkc.getSessionId()
+ " client bean:" + clientBean.toString());
childItr.remove();
}
}
}
}
for (ObjectName bean : children) {
LOG.info("unexpected:" + bean.toString());
}
TestCase.assertEquals("Unexpected bean exists!", 0, children.size());
}
示例8: runHammer
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
public void runHammer(final int threadCount, final int childCount)
throws Throwable
{
try {
HammerThread[] threads = new HammerThread[threadCount];
long start = System.currentTimeMillis();
for (int i = 0; i < threads.length; i++) {
ZooKeeper zk = createClient();
String prefix = "/test-" + i;
zk.create(prefix, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
prefix += "/";
HammerThread thread =
new BasicHammerThread("BasicHammerThread-" + i, zk, prefix,
childCount);
thread.start();
threads[i] = thread;
}
verifyHammer(start, threads, childCount);
} catch (Throwable t) {
LOG.error("test Assert.failed", t);
throw t;
}
}
示例9: process
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
@Override
public void process(WatchedEvent event) {
ZooKeeper zkClient = zookeeperConnManager.getZkClient();
try {
/* 重新注册节点 */
List<String> childrens = zkClient.getChildren(nodePath, this);
EventType eventType = event.getType();
switch (eventType) {
case NodeChildrenChanged:
log.info("当前注册中心内的成功注册的agent数量-->"
+ childrens.stream().filter(children -> children.startsWith("agent")).count());
break;
default:
break;
}
} catch (Exception e) {
log.error("error", e);
}
}
示例10: waitForAll
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
private void waitForAll(ZooKeeper[] zks, States state) throws InterruptedException {
int iterations = 10;
boolean someoneNotConnected = true;
while(someoneNotConnected) {
if (iterations-- == 0) {
ClientBase.logAllStackTraces();
throw new RuntimeException("Waiting too long");
}
someoneNotConnected = false;
for(ZooKeeper zk: zks) {
if (zk.getState() != state) {
someoneNotConnected = true;
}
}
Thread.sleep(1000);
}
}
示例11: testClientRetry
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
@Test
public void testClientRetry() throws IOException, InterruptedException, TimeoutException{
CountdownWatcher cdw1 = new CountdownWatcher();
CountdownWatcher cdw2 = new CountdownWatcher();
ZooKeeper zk = new ZooKeeper(hostPort, 10000, cdw1);
try {
cdw1.waitForConnected(CONNECTION_TIMEOUT);
ZooKeeper zk2 = new ZooKeeper(hostPort, 10000, cdw2);
try {
States s1 = zk.getState();
States s2 = zk2.getState();
Assert.assertSame(s1,States.CONNECTED);
Assert.assertSame(s2,States.CONNECTING);
cdw1.reset();
cdw1.waitForDisconnected(CONNECTION_TIMEOUT);
cdw2.waitForConnected(CONNECTION_TIMEOUT);
Assert.assertSame(zk2.getState(),States.CONNECTED);
} finally {
zk2.close();
}
} finally {
zk.close();
}
}
示例12: testRemove1
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
@Test
public void testRemove1() throws Exception{
String dir = "/testRemove1";
String testString = "Hello World";
final int num_clients = 1;
ZooKeeper clients[] = new ZooKeeper[num_clients];
DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
for(int i=0; i < clients.length; i++){
clients[i] = createClient();
queueHandles[i] = new DistributedQueue(clients[i], dir, null);
}
try{
queueHandles[0].remove();
}catch(NoSuchElementException e){
return;
}
Assert.assertTrue(false);
}
示例13: createNremoveMelementTest
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
public void createNremoveMelementTest(String dir,int n,int m) throws Exception{
String testString = "Hello World";
final int num_clients = 2;
ZooKeeper clients[] = new ZooKeeper[num_clients];
DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
for(int i=0; i < clients.length; i++){
clients[i] = createClient();
queueHandles[i] = new DistributedQueue(clients[i], dir, null);
}
for(int i=0; i< n; i++){
String offerString = testString + i;
queueHandles[0].offer(offerString.getBytes());
}
byte data[] = null;
for(int i=0; i<m; i++){
data=queueHandles[1].remove();
}
Assert.assertEquals(new String(queueHandles[1].element()), testString+m);
}
示例14: findPrefixInChildren
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
/** find if we have been created earler if not create our node
*
* @param prefix the prefix node
* @param zookeeper teh zookeeper client
* @param dir the dir paretn
* @throws KeeperException
* @throws InterruptedException
*/
private void findPrefixInChildren(String prefix, ZooKeeper zookeeper, String dir)
throws KeeperException, InterruptedException {
List<String> names = zookeeper.getChildren(dir, false);
for (String name : names) {
if (name.startsWith(prefix)) {
id = name;
if (LOG.isDebugEnabled()) {
LOG.debug("Found id created last time: " + id);
}
break;
}
}
if (id == null) {
id = zookeeper.create(dir + "/" + prefix, data,
getAcl(), EPHEMERAL_SEQUENTIAL);
if (LOG.isDebugEnabled()) {
LOG.debug("Created id: " + id);
}
}
}
示例15: testNodeCreated
import org.apache.zookeeper.ZooKeeper; //导入依赖的package包/类
@Test
public void testNodeCreated() throws Exception {
QuorumUtil qu = new QuorumUtil(1);
qu.startAll();
EventsWatcher watcher = new EventsWatcher();
ZooKeeper zk1 = createClient(qu, 1, watcher);
ZooKeeper zk2 = createClient(qu, 2);
String path = "/test1-created";
zk1.exists(path, watcher);
qu.shutdown(1);
zk2.create(path, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
qu.start(1);
watcher.waitForConnected(TIMEOUT * 1000L);
watcher.assertEvent(TIMEOUT, EventType.NodeCreated);
qu.shutdownAll();
}