会话重连机制

ZKConnectSessionWatcher.java

/**
 * 
 * @Title: ZKConnectDemo.java
 * @Description: zookeeper 恢复之前的会话连接demo
 */
public class ZKConnectSessionWatcher implements Watcher {

    final static Logger log = LoggerFactory.getLogger(ZKConnectSessionWatcher.class);

    public static final String zkServerPath = "192.168.1.110:2181";
    public static final Integer timeout = 5000;

    public static void main(String[] args) throws Exception {

        ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, new ZKConnectSessionWatcher());

        //sessionId,sessionPassword 用于后面会话重连
        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());
        new Thread().sleep(1000);
        log.warn("连接状态:{}", zk.getState());

        new Thread().sleep(200);

        // 开始会话重连
        log.warn("开始会话重连...");

        ZooKeeper zkSession = new ZooKeeper(zkServerPath, 
                                            timeout, 
                                            new ZKConnectSessionWatcher(), 
                                            sessionId, 
                                            sessionPassword);
        log.warn("重新连接状态zkSession:{}", zkSession.getState());
        new Thread().sleep(1000);
        log.warn("重新连接状态zkSession:{}", zkSession.getState());
    }

    @Override
    public void process(WatchedEvent event) {
        log.warn("接受到watch通知:{}", event);
    }
}

通过debug进行一步一步调试进行,使用一下命令查看一下会话

[dump] 列出未经处理的会话和临时节点

$ echo dump | grep localhost 2181

Last updated