本文共 3232 字,大约阅读时间需要 10 分钟。
Zookeeper 可作为注册中心,实现服务注册与发现,当服务启动后,就会注册到 Zookeeper,然后保存该服务的地址以以及一些基本的信息,其他服务可从注册中心获取到该服务的地址,进行 RPC 远程调用,和 Eureka 作为注册中心同理,Eureka 和 Zookeeper 的区别在于 Eureka 保证 AP,也就是保证高可用和分区容错,Zookeeper 保证 CP,也就是保证一致性和分区容错。
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-logging com.101tec zkclient 0.8
编写一个类实现 ApplicationRunner 接口,然后注册到 Spring 容器中,当我们启动 Spring 项目后,就会执行以下代码把该服务注册到 Zookeeper,我们可以修改 yml 配置文件中的端口号,分别注册多个实例。
@Componentpublic class MyApplicationRunner implements ApplicationRunner { @Value("${server.port}") private String port; private static CountDownLatch countDownLatch = new CountDownLatch(1); @Override public void run(ApplicationArguments args) throws Exception { ZooKeeper zooKeeper = new ZooKeeper("10.13.1.171:2181", 5000, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { //获取连接状态 Event.KeeperState state = watchedEvent.getState(); if (state == Event.KeeperState.SyncConnected) { System.out.println("zk连接成功"); countDownLatch.countDown(); } } }); countDownLatch.await(); String parentPath = "/user-service"; Stat exits = zooKeeper.exists(parentPath, null); if (exits == null) { zooKeeper.create(parentPath,"user".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } String path = "http://127.0.0.1"+port; zooKeeper.create(parentPath+"/"+port,path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); System.out.println("服务注册成功!"); }}
public class ZkTest { //计数器 private static CountDownLatch countDownLatch = new CountDownLatch(1); public static void main(String[] args) throws IOException, KeeperException, InterruptedException { /** * 1、连接地址 * 2、超时时间 * 3、事件通知 */ ZooKeeper zooKeeper = new ZooKeeper("10.13.1.171:2181", 5000, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { //获取连接状态 Event.KeeperState state = watchedEvent.getState(); if (state == Event.KeeperState.SyncConnected) { System.out.println("zk连接成功"); countDownLatch.countDown(); } } }); countDownLatch.await(); String path = "/user-service"; Listchildren = zooKeeper.getChildren(path, null, new Stat()); for (int i = 0; i < children.size(); i++) { String pathChildren = path + "/" + children.get(i); byte[] data = zooKeeper.getData(pathChildren, null, new Stat()); System.out.println("服务地址:" + new String(data)); } }}
https://github.com/huangliangyun/Spring-Boot-2.X/tree/master/spring-boot-zookeeper
公众号:【星尘Pro】
github:
推荐阅读
转载地址:http://dyfsi.baihongyu.com/