Java 使用zookeeper原声API进行操作

目录


zookeeper API介绍

导入依赖项

操作代码示例 

 

 


 

 

 

 

 

zookeeper API介绍

   Zookeeper官方为Java提供了Zookeeper API,但是Zookeeper API并不好用,只需要了解一下即可,以后可以使用ZkClient(对Zookeeper API做了封装)。

 

导入依赖项

  因为zookeeper依赖的jar包比较多,所以推荐使用Maven来管理以来,只需要在pom.xml的依赖中添加下面的内容即可:

<dependency>
	<groupId>org.apache.zookeeper</groupId>
	<artifactId>zookeeper</artifactId>
	<version>3.4.14</version>
	<type>pom</type>
</dependency>

  

 

操作示例代码

package cn.ganlixin.test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class ZookeeperAPI {

	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
		
		// 创建一个countDownLatch,用来管理程序运行进度
		CountDownLatch countDownLatch = new CountDownLatch(1);
		
		// 连接串
		//String connectString = "127.0.0.1:2181; 127.0.0.1:2182; 127.0.0.1:2183";

		// 会话超时时间
		int sessionTimeout = 2000;
		
		// 创建zookeeper连接(是异步连接,所以需要让主线程阻塞,在连接成功后,让主线程继续执行)
		ZooKeeper zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// 事件类型
				EventType type = event.getType();
				// 时间状态
				KeeperState state = event.getState();
				
				if (state == KeeperState.SyncConnected) {
					if (type == EventType.None) {
						System.out.println("成功连接Zookeeper服务器");
						countDownLatch.countDown(); // 让主线程继续运行
					}
				}
			}
		});
		// 阻塞,等待countDownLatch减为0即可继续运行
		countDownLatch.await();
		
		// 利用创建的zk连接,进行各种操作
		zk.create("/test", "hello world".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		
		byte[] data = zk.getData("/test", null, null);
		System.out.println(new String(data, 0, data.length));
		
		// 关闭连接
		zk.close();
	}
}

  

posted @ 2019-06-09 15:41 寻觅beyond 阅读(...) 评论(...) 编辑 收藏
Flag Counter