1.链接zookeeper

String zkServers ="localhost:2181,localhost:2182,localhost:2183";
     /*public ZkClient(String zkServers, int sessionTimeout, int connectionTimeout, ZkSerializer zkSerializer) {
        this(new ZkConnection(zkServers, sessionTimeout), connectionTimeout, zkSerializer);}*/

     ZkClient zkClient = new ZkClient(zkServers,10000,10000,new SerializableSerializer());
     System.out.println("conneced Ok");

2创建节点

//创建节点.持久化的的节点
    User user = new User();
    user.setId(1);
    user.setName("laowang");
   
   
    String path = zkClient.create("/testNode2", user, CreateMode.PERSISTENT);
    System.out.println("创建节点"+path);

3创建监听

创建class

public class zkListener implements IZkChildListener {


public void handleChildChange(String parentpath, List<String> children) throws Exception {
System.out.println(parentpath);
System.out.println(children.toString());
}


}


4.监听子节点变化

zkClient.subscribeChildChanges("/testNode4", new zkListener());
    Thread.sleep(Integer.MAX_VALUE);


5打开zkCli.cmd(前提是开启zookeeper的zkServer.cmd)



Logo

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

更多推荐