来源: https://www.cnblogs.com/LiZhiW/p/4923693.html

  1. 安装zk,并启动(步骤略)
  2. 创建springboot项目
  3. 添加依赖
<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		//上述文章说了,最好的zk客户端,反正肯定比自己实现的强,就用这个了
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-framework</artifactId>
			<version>4.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-client</artifactId>
			<version>4.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-recipes</artifactId>
			<version>4.0.1</version>
		</dependency>
	<dependency>
			<groupId>org.apache.zookeeper</groupId>
			<artifactId>zookeeper</artifactId>
			<version>3.4.10</version>
		</dependency>
	</dependencies>
	//以上仅做zk,不需要其他多余的依赖
  1. 不需要配置文件, 直接进入代码操作
private final static String zkaddr = "ip:2181";
	
	public static void main(String[] args) throws Exception {
		getNodes();
	}
	
	public static void getNodes() throws Exception {
		CuratorFramework client = CuratorFrameworkFactory
				.newClient(zkaddr, 1000*60, 1000*15, new RetryNTimes(10,5000));
		client.start();//开始连接
		CuratorFrameworkState st = client.getState();
		System.out.println(st);
		List<String> children = client.getChildren().usingWatcher(new CuratorWatcher() {
			@Override
			public void process(WatchedEvent event) throws Exception {
				System.out.println("监控: " + event);
			}
		}).forPath("/");
		System.out.println(children);
		String result = client.create().withMode(CreateMode.PERSISTENT).withACL(Ids.OPEN_ACL_UNSAFE).forPath("/test", "Data".getBytes());
	    System.out.println(result);
	    // 设置节点数据
	    client.setData().forPath("/test", "111".getBytes());
	    client.setData().forPath("/test", "222".getBytes());
	    // 删除节点
	    System.out.println(client.checkExists().forPath("/test"));
	    client.delete().withVersion(-1).forPath("/test");
	    System.out.println(client.checkExists().forPath("/test"));
	    client.close();
	    System.out.println("OK!");
	    client.getCuratorListenable().addListener(new CuratorListener()
	    {
	        @Override
	        public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception
	        {
	            System.out.println("事件: " + event);
	        }
	    });
	    client.getConnectionStateListenable().addListener(new ConnectionStateListener()
	    {
	        @Override
	        public void stateChanged(CuratorFramework client, ConnectionState newState)
	        {
	            System.out.println("连接状态事件: " + newState);
	        }
	    });
	    client.getUnhandledErrorListenable().addListener(new UnhandledErrorListener()
	    {
	        @Override
	        public void unhandledError(String message, Throwable e)
	        {
	            System.out.println("错误事件:" + message);
	        }
	    });
	}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐