Zookeeper 重连机制
public class ZKConnectSessionWatcher implements Watcher { public final static String zkServerPath = "10.10.10.10:2181"; public final static int 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("客户端开始连接Zookeeper服务器..."); log("连接状态:" + zk.getState()); new Thread().sleep(1000); log("连接状态:" + zk.getState()); log("开始会话重连。。。"); ZooKeeper zkSession = new ZooKeeper(zkServerPath, timeout, new ZKConnectSessionWatcher(), sessionId, sessionPassword); log("重新连接zkSession:" + zkSession.getState()); new Thread().sleep(1000); log("重新连接zkSession:" + zkSession.getState()); } public void process(WatchedEvent event) { System.out.println("接收到watch通知:" + event.toString()); } private static void log(String msg){ System.out.println(msg); }