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();
String ssid = "0x" + Long.toHexString(sessionId);
System.out.println(ssid);
byte[] sessionPassword = zk.getSessionPasswd();
log.warn("客户端开始连接zookeeper服务器...");
log.warn("连接状态:{}", zk.getState());
Thread.sleep(1000);
log.warn("连接状态:{}", zk.getState());
Thread.sleep(6000);
// 开始会话重连
log.warn("开始会话重连...");
ZooKeeper zkSession = new ZooKeeper(zkServerPath,
timeout,
new ZKConnectSessionWatcher(),
sessionId,
sessionPassword);
log.warn("重新连接状态zkSession:{}", zkSession.getState());
Thread.sleep(1000);
log.warn("重新连接状态zkSession:{}", zkSession.getState());
}
@Override
public void process(WatchedEvent event) {
log.warn("接受到watch通知:{}", event);
}
}
2018-10-01 17:24:08,001 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:29)] - [WARN] 客户端开始连接zookeeper服务器…
2018-10-01 17:24:08,005 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:30)] - [WARN] 连接状态:CONNECTING
2018-10-01 17:24:08,027 [main-EventThread] [com.imooc.zk.demo.ZKConnectSessionWatcher.process(ZKConnectSessionWatcher.java:48)] - [WARN] 接受到watch通知:WatchedEvent state:SyncConnected type:None path:null
2018-10-01 17:24:09,006 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:32)] - [WARN] 连接状态:CONNECTED
2018-10-01 17:24:15,007 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:35)] - [WARN] 开始会话重连…
2018-10-01 17:24:15,022 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:41)] - [WARN] 重新连接状态zkSession:CONNECTING
2018-10-01 17:24:15,038 [main-EventThread] [com.imooc.zk.demo.ZKConnectSessionWatcher.process(ZKConnectSessionWatcher.java:48)] - [WARN] 接受到watch通知:WatchedEvent state:SyncConnected type:None path:null
Disconnected from the target VM, address: ‘127.0.0.1:50181’, transport: 'socket’
2018-10-01 17:24:16,022 [main] [com.imooc.zk.demo.ZKConnectSessionWatcher.main(ZKConnectSessionWatcher.java:43)] - [WARN] 重新连接状态zkSession:CONNECTED