Zookeeper | Zookeeper 实现服务注册与发现

一、简介

Zookeeper 可作为注册中心,实现服务注册与发现,当服务启动后,就会注册到 Zookeeper,然后保存该服务的地址以以及一些基本的信息,其他服务可从注册中心获取到该服务的地址,进行 RPC 远程调用,和 Eureka 作为注册中心同理,Eureka 和 Zookeeper 的区别在于 Eureka 保证 AP,也就是保证高可用和分区容错,Zookeeper 保证 CP,也就是保证一致性和分区容错。

二、实例

1、创建 SpringBoot 项目添加依赖
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>com.101tec</groupId>
			<artifactId>zkclient</artifactId>
			<version>0.8</version>
		</dependency>
	</dependencies>
2、编写服务注册代码

编写一个类实现 ApplicationRunner 接口,然后注册到 Spring 容器中,当我们启动 Spring 项目后,就会执行以下代码把该服务注册到 Zookeeper,我们可以修改 yml 配置文件中的端口号,分别注册多个实例。

@Component
public 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("服务注册成功!");
    }
}

在这里插入图片描述
在这里插入图片描述

3、编写服务发现代码
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";
        List<String> children = 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

ABOUT

我的 Github:Github
CSDN: CSDN
个人网站: sirius blog
E-mail: [email protected]

推荐阅读
史上最全,最完美的 JAVA 技术体系思维导图总结,没有之一!
全站导航 | 我为什么要写这些博客?

发布了81 篇原创文章 · 获赞 373 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/Sirius_hly/article/details/104721443