搭建zookeeper

使用docker运行zookeeper:

  1. $ docker pull zookeeper
  2. $ docker images zookeeper
  3. REPOSITORY TAG IMAGE ID CREATED SIZE
  4. zookeeper latest 3f1e19bd8ecc 8 days ago 278MB
  5. $ docker run --name zookeeper --restart always -e JVMFLAGS="-Xmx256m" -p 2181:2181 -d zookeeper

进入容器内,使用zookeeper client:

  1. $ docker exec -it zookeeper /bin/bash
  2. $ cd /apache-zookeeper-3.7.0-bin/bin/
  3. $ ./zkCli.sh
  4. ...
  5. [zk: localhost:2181(CONNECTED) 1] ls /
  6. [zookeeper]

使用zookeeper作为注册中心

在pom.xml中添加依赖:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
  4. </dependency>

在启动类中增加注解@EnableDiscoveryClient

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. public class PaymentMain8004 {
  4. public static void main(String[] args) {
  5. SpringApplication.run(PaymentMain8004.class, args);
  6. }
  7. }

在application.yml中增加zookeeper配置:

  1. spring:
  2. application:
  3. name: cloud-payment-service
  4. cloud:
  5. zookeeper:
  6. connect-string: 127.0.0.1:2181

启动Spring Boot服务后,在zookeeper client中查服务是否注册成功:

  1. [zk: localhost:2181(CONNECTED) 2] ls /
  2. [services, zookeeper]
  3. [zk: localhost:2181(CONNECTED) 3] ls /services
  4. [cloud-payment-service]