springboot 连接zookeeper ,添加节点

pom.xml  依赖 

        
	       org.apache.zookeeper
			zookeeper
			3.4.14
		

代码: countdownlatch  防止 还没连接就操作节点。 注释了信号量等待就会报错, 因为zk创建连接是一个子线程, 创建节点是在主线程。

springboot 连接zookeeper ,添加节点_第1张图片

        private static final String address = "192.168.xxx.xxx:2181";
		private static final int session_timeout = 5000;
		private static final CountDownLatch cout = new CountDownLatch(1);
	
		public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
				ZooKeeper zk = new ZooKeeper(address, session_timeout, new Watcher() {
					// 事件通知
					@Override
					public void process(WatchedEvent event) 
					{
						// 事件状态
						KeeperState state = event.getState();
						// 连接状态
						if (KeeperState.SyncConnected == state) 
						{
							EventType type = event.getType();
							// 事件类型
							if (EventType.None == type)
							{
								cout.countDown();
								System.out.println("--------zk开始连接.");
							}
						}
					}
				});
				
				cout.await();
				//创建节点
				String create = zk.create("/tangjiandong_tang", "dong".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
				System.out.println("-------创建节点: " + create);
				zk.close();
		}

 可视化工具查看zk节点:节点已经创建成功。

下载地址; https://issues.apache.org/jira/secure/attachment/12436620/ZooInspector.zip;

 

springboot 连接zookeeper ,添加节点_第2张图片

 

启动可视化工具及 开始连接zookeeper

springboot 连接zookeeper ,添加节点_第3张图片 

你可能感兴趣的:(程序人生)