搭建zookeeper
使用docker运行zookeeper:
$ docker pull zookeeper
$ docker images zookeeper
REPOSITORY TAG IMAGE ID CREATED SIZE
zookeeper latest 3f1e19bd8ecc 8 days ago 278MB
$ docker run --name zookeeper --restart always -e JVMFLAGS="-Xmx256m" -p 2181:2181 -d zookeeper
进入容器内,使用zookeeper client:
$ docker exec -it zookeeper /bin/bash
$ cd /apache-zookeeper-3.7.0-bin/bin/
$ ./zkCli.sh
...
[zk: localhost:2181(CONNECTED) 1] ls /
[zookeeper]
使用zookeeper作为注册中心
在pom.xml中添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
在启动类中增加注解@EnableDiscoveryClient
:
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain8004 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8004.class, args);
}
}
在application.yml中增加zookeeper配置:
spring:
application:
name: cloud-payment-service
cloud:
zookeeper:
connect-string: 127.0.0.1:2181
启动Spring Boot服务后,在zookeeper client中查服务是否注册成功:
[zk: localhost:2181(CONNECTED) 2] ls /
[services, zookeeper]
[zk: localhost:2181(CONNECTED) 3] ls /services
[cloud-payment-service]