Zookeeper分布式命名服务实战
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class DistributedServiceRegistry {
private static CountDownLatch connectedSignal = new CountDownLatch(1);
private static ZooKeeper zk;
// 连接到Zookeeper服务
public static void connectToZookeeper(String hosts) throws IOException, InterruptedException {
zk = new ZooKeeper(hosts, 3000, event -> {
if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
connectedSignal.countDown();
}
});
connectedSignal.await();
}
// 注册服务
public static void registerService(String serviceName, String serviceAddress) throws KeeperException, InterruptedException {
String createPath = zk.create("/" + serviceName, serviceAddress.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println("Service registered with path: " + createPath);
}
// 获取服务列表
public static List<String> getServiceList(String serviceName) throws KeeperException, InterruptedException {
List<String> services = zk.getChildren("/" + serviceName, false).stream()
.map(path -> {
try {
return new String(zk.getData("/" + serviceName + "/" + path, false, new Stat()));
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
return services;
}
public static void main(String[] args) {
try {
connectToZookeeper("localhost:2181");
registerService("services/myService", "127.0.0.1:8080");
List<String> services = getServiceList("services/myService");
services.forEach(System.out::println);
} catch (IOException | InterruptedException | KeeperException e) {
e.printStackTrace();
}
}
}
这个简化版的实例代码展示了如何使用Zookeeper的Java API来实现一个简单的服
评论已关闭