连不上Zookeeper

连不上Zookeeper

老师测试一下

package com.imooc.zkjavaapi.watcher;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

/**
 * 描述:      连接Watcher
 */
public class ConnectWatcher implements Watcher {


    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("ConnectWatcher的process被调用了");
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("连接成功");
        }
        if (watchedEvent.getState() == Event.KeeperState.Closed) {
            System.out.println("连接关闭");
        }
    }

}
package com.imooc.zkjavaapi;

import com.imooc.zkjavaapi.watcher.ConnectWatcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

import java.io.IOException;

/**
 * 描述:   连接到ZK
 */
public class FirstConnect {

    public static void main(String[] args) throws IOException, InterruptedException {
        ConnectWatcher connectWatcher = new ConnectWatcher();
        ZooKeeper zk = new ZooKeeper(ZKConstant.ZK_HOST, ZKConstant.CONNECT_TIMEOUT, connectWatcher);
        System.out.println("客户端开始连接ZK服务器");
        States state = zk.getState();
        System.out.println(state);
        Thread.sleep(2000);
        state = zk.getState();
        System.out.println(state);
        Thread.sleep(2000);
        zk.close();

    }
}
package com.imooc.zkjavaapi;

/**
 * 描述:     ZK常量类
 */
public class ZKConstant {

    public static final String ZK_HOST = "192.168.172.134:2181";
    public static final Integer CONNECT_TIMEOUT = 3000;
}

https://img1.sycdn.imooc.com//climg/64c86a60096f8de711510702.jpg

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕小尤 2023-08-01 11:26:42

同学你好,1、测试同学代码是可以实现连接的,如下所示:

https://img1.sycdn.imooc.com//climg/64c87ace09544e8a08230281.jpg

2、建议检查是否有成功启动Zookeeper。

3、如果还存在问题,建议同学安装本地Zookeeper,然后启动试一下。

https://img1.sycdn.imooc.com//climg/64c87b540905ea5703160326.jpg

祝学习愉快!

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师