# docker compose版本
version: "3.1"
services:
# 节点1
zk1:
# 镜像名称
image: zookeeper
# 容器名称
container_name: zk1.docker
# docker重启后自动重启容器
restart: always
# 当前容器主机名
hostname: zk1.docker
# 端口 宿主机:容器
ports:
- 2181:2181
# 环境变量
environment:
# myid,一个集群内唯一标识一个节点
ZOO_MY_ID: 1
# 集群内节点列表
ZOO_SERVERS:
- server.1=zk1.docker:2888:3888;2181
- server.2=zk2.docker:2888:3888;2181
- server.3=zk3.docker:2888:3888;2181
# 节点2
zk2:
image: zookeeper
container_name: zk2.docker
restart: always
hostname: zk2.docker
ports:
- 2182:2181
environment:
ZOO_MY_ID: 2
ZOO_SERVERS:
- server.1=zk1.docker:2888:3888;2181
- server.2=zk2.docker:2888:3888;2181
- server.3=zk3.docker:2888:3888;2181
# 节点3
zk3:
image: zookeeper
container_name: zk3.docker
restart: always
hostname: zk3.docker
ports:
- 2183:2181
environment:
ZOO_MY_ID: 3
ZOO_SERVERS:
- server.1=zk1.docker:2888:3888;2181
- server.2=zk2.docker:2888:3888;2181
- server.3=zk3.docker:2888:3888;2181
docker-compose -f zk-replicated.yml up
bin/zkServer.sh status
package com.futao.zookeeper.dynamic;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 客户端监听服务实例的变化
*
* @author ft
* @date 2021/8/3
*/
@Slf4j
public class Client {
private static ZooKeeper Zk = null;
/**
* 集群地址
*/
private static final String CONNECT_STRING = "localhost:2181,localhost:2182,localhost:2183";
public static void main(String[] args) throws IOException, InterruptedException {
Zk = new ZooKeeper(CONNECT_STRING, 2000, new Watcher() {
@SneakyThrows
@Override
public void process(WatchedEvent event) {
Stat stat = Zk.exists("/server-pig", false);
if (stat == null) {
Zk.create("/server-pig", "".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
log.info("创建/server-pig成功");
}
// 可用的实例列表
List<String> serverList = new ArrayList<>();
List<String> children = Zk.getChildren("/server-pig", true);
for (String child : children) {
byte[] data = Zk.getData("/server-pig/" + child, false, null);
// 拿到的是节点名,而不是data,why?
serverList.add(new String(data));
}
System.out.println(children);
}
});
// 阻塞主线程
TimeUnit.HOURS.sleep(1);
}
}
集群搭建完成