public class ZKConnectSessionWatcher implements Watcher {
final static Logger log = LoggerFactory.getLogger(ZKConnectSessionWatcher.class);
public static final String zkServerPath = "192.168.0.130:2181";
public static final Integer timeout = 5000;
public static void main(String[] args) throws Exception {
ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, new ZKConnectSessionWatcher());
long sessionId = zk.getSessionId();
byte[] sessionPassword = zk.getSessionPasswd();
log.warn("客户端开始连接zookeeper服务器...");
log.warn("连接状态:{}", zk.getState());
Thread.sleep(1000);
log.warn("连接状态:{}", zk.getState());
String result = zk.create("/test", "456".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Thread.sleep(12000);
System.out.println("睡六秒后的状态:"+zk.getState());
// 开始会话重连
log.warn("开始会话重连...");
ZooKeeper zkSession = new ZooKeeper(zkServerPath,
timeout,
new ZKConnectSessionWatcher(),
sessionId,
sessionPassword);
log.warn("重新连接状态zkSession:{}", zkSession.getState());
Thread.sleep(1000);
String ctx = "{'callback':'ChildrenCallback'}";
List<String> children = zk.getChildren("/", true);
for (String child : children) {
System.out.println(child);
}
log.warn("重新连接状态zkSession:{}", zkSession.getState());
}
@Override
public void process(WatchedEvent event) {
log.warn("接受到watch通知:{}", event);
}
}
2018-10-01 20:40:45,679 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:27)] - [WARN] 客户端开始连接zookeeper服务器…
2018-10-01 20:40:45,683 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:28)] - [WARN] 连接状态:CONNECTING
2018-10-01 20:40:45,701 [main-EventThread] [com.imooc.zk.demo.ZKConnectSessionWatcher.process(ZKConnectSessionWatcher.java:56)] - [WARN] 接受到watch通知:WatchedEvent state:SyncConnected type:None path:null
2018-10-01 20:40:46,683 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:30)] - [WARN] 连接状态:CONNECTED
睡六秒后的状态:CONNECTED
2018-10-01 20:40:58,692 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:36)] - [WARN] 开始会话重连…
2018-10-01 20:40:58,704 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:43)] - [WARN] 重新连接状态zkSession:CONNECTING
2018-10-01 20:40:58,720 [main-EventThread] [com.imooc.zk.demo.ZKConnectSessionWatcher.process(ZKConnectSessionWatcher.java:56)] - [WARN] 接受到watch通知:WatchedEvent state:SyncConnected type:None path:null
dubbo
test
zookeeper
names
test-delete-node
testnode
imooc
2018-10-01 20:40:59,706 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:51)] - [WARN] 重新连接状态zkSession:CONNECTED
老师,已经12秒了。超过两倍的心跳时间了,为什么临时节点test还是存在