在 CentOS 上配置 Zookeeper 的 Java 客户端
一 环境准备
二 获取并引入客户端依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.7.0</version>
</dependency>
implementation 'org.apache.zookeeper:zookeeper:3.7.0'
三 客户端连接配置与示例代码
import org.apache.zookeeper.*;
public class ZkClientDemo {
public static void main(String[] args) throws Exception {
// 替换为你的 Zookeeper 地址与端口
String connectionString = "192.168.1.100:2181";
int sessionTimeout = 3000;
ZooKeeper zk = new ZooKeeper(connectionString, sessionTimeout, event -> {
System.out.println("Received event: " + event);
});
// 简单读取根节点子节点
System.out.println("Children of /: " + zk.getChildren("/", false));
// 关闭连接
zk.close();
}
}
四 网络与防火墙设置
sudo firewall-cmd --add-port=2181/tcp --permanent
sudo firewall-cmd --reload
sudo systemctl stop firewalld
五 常见问题与排查