Zookeeper服务注册与发现,Docker安装(CP)

Posted by Beyonderwei on 2020-11-26
Words 482 and Reading Time 2 Minutes
Viewed Times

Zookeeper由Java语言编写。

一、安装

  • 搜索Zookeeper

    docker search zookeeper

  • 拉取指定版本

    docker pull zookeerper:3.6.2

  • 运行镜像

    docker run --name 容器名 -p 2181:2181 --restart always -d 镜像id

    • 启动后会EXPOSE端口:2181(对client端提供服务), 2888(选举leader使用), 3888(集群内机器通讯使用)。
    • 并设置为始终重启。

二、使用Zookeeper

  • 进入容器

    docker exec -it 容器ID bash

  • 启动Zookeeper

    ./bin/zkCli.sh

  • 查看Zookeeper节点

    ls /zookeeper

  • 注册成功后会在根目录下有services节点

    ls /

  • 查看注册到Zookeeper的服务

    ls /services

  • 得到微服务ID

    ls /services/服务名

  • 获得注册信息

    get /services/服务名/服务ID

三、临时节点

微服务注册到 Zookeeper 后,同样依靠心跳包进行连接,如果超过一定时间连接不到微服务发送的心跳,则直接将注册信息删除,重新连接后也不会恢复,而是重新注册。

四、服务注册

1. 微服务(服务提供方)

  • pom依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
    <!--排除zk3.5.3-->
    <exclusions>
    <exclusion>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    </exclusion>
    </exclusions>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
    <dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.6.2</version>
    </dependency>
  • yaml配置文件

    1
    2
    3
    4
    5
    6
    spring:
    application:
    name: cloud-provider-payment
    cloud:
    zookeeper:
    connect-string: 42.192.52.13:2181
  • 启动类添加注解

    1
    @EnableDiscoveryClient

2. 服务调用方

  • pom

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
    </dependency>
  • yaml配置文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    server:
    port: 80

    spring:
    application:
    name: cloud-consumer-order
    cloud:
    zookeeper:
    connect-string: 42.192.52.13:2181
  • 启动类加注解

    1
    @EnableDiscoveryClient
  • RestTemplate配置类的创建方法添加注解 @LoadBalanced 负载均衡

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Configuration
    public class ApplicationContextConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
    return new RestTemplate();
    }
    }

本文为作者原创文章,未经作者允许不得转载。

...

...

00:00
00:00