【README】搭建zk cluster, refer 2 https://blog.csdn.net/PacosonSWJTU/article/details/111404364
【1】 动态监听代码,需要写在 建立zk 连接的watcher 实现类里,如下:
public class TestZK {/*** zk server 连接串 */private String connectString = "192.168.163.201:2181,192.168.163.202:2181,192.168.163.203:2181";/*** 超时时间*/private int sessionTimeout = 3000; /*** zk客户端实例 */private ZooKeeper zkClient; /*** 0-获取zk连接 * @throws IOException*/@Before public void init() throws IOException {/* 连接zk服务器 */zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {@Overridepublic void process(WatchedEvent event) {try {/*3-获取子节点并监控节点变化*/System.out.println("-------watcher start---------");zkClient.getChildren("/", true).stream().forEach(System.out::println);System.out.println("-------watcher end ---------");} catch (KeeperException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}});}/*** 2-获取子节点 * @throws InterruptedException * @throws KeeperException */@Testpublic void getNode() throws KeeperException, InterruptedException {System.out.println("-------getNode start---------");zkClient.getChildren("/", false).stream().forEach(System.out::println);System.out.println("-------getNode end---------");try {System.in.read(); // 阻塞,主线程不结束 } catch (IOException e) {e.printStackTrace();} }/*sichuanzookeeperstar*/}
【2】 centos8 zk 客户端新建和删除节点
log: zk client operation on centos 8
[zk: localhost:2181(CONNECTED) 0] ls /
[sichuan, zookeeper, guangdong]
[zk: localhost:2181(CONNECTED) 1] rmr /guangdong
[zk: localhost:2181(CONNECTED) 2]
[zk: localhost:2181(CONNECTED) 2] ls /
[sichuan, zookeeper]
[zk: localhost:2181(CONNECTED) 3] create /shanghai "shanghai city"
Created /shanghai
[zk: localhost:2181(CONNECTED) 4] ls /
[shanghai, sichuan, zookeeper]
[zk: localhost:2181(CONNECTED) 5] create /beijing "beijinj city"
Created /beijing
[zk: localhost:2181(CONNECTED) 6] ls /
[shanghai, sichuan, beijing, zookeeper]
[zk: localhost:2181(CONNECTED) 7]
java log
-------getNode start---------
2020-12-19 15:07:05,968 INFO [org.apache.zookeeper.ClientCnxn] - Opening socket connection to server 192.168.163.201/192.168.163.201:2181. Will not attempt to authenticate using SASL (unknown error)2020-12-19 15:07:06,004 INFO [org.apache.zookeeper.ClientCnxn] - Socket connection established to 192.168.163.201/192.168.163.201:2181, initiating session2020-12-19 15:07:06,011 INFO [org.apache.zookeeper.ClientCnxn] - Session establishment complete on server 192.168.163.201/192.168.163.201:2181, sessionid = 0x1767ab9b8f10001, negotiated timeout = 4000-------watcher start---------
sichuan
zookeeper
guangdong
-------watcher end ---------
sichuan
zookeeper
guangdong
-------getNode end---------
-------watcher start---------
sichuan
zookeeper
-------watcher end ---------
-------watcher start---------
shanghai
sichuan
zookeeper
-------watcher end ---------
-------watcher start---------
shanghai
sichuan
beijing
zookeeper
-------watcher end ---------
bingo !