一、docker环境下部署zookeeper
1.下拉镜像2.部署容器 二、SpringCloud向zookeeper中注册服务
1.引入jar包2.完成pom文件内容3.配置application.yml4.使用@EnableDiscoveryClient注解声明main方法5.启动服务查看zookeeper中注册的服务 三、微服务间方法调用
1. 声明RestTemplate模板2. 调用接口3.请求结果 总结
一、docker环境下部署zookeeper 1.下拉镜像
docker pull zookeeper2.部署容器
docker run --privileged=true -d --name zookeeper --publish 2181:2181 -d zookeeper:latest二、SpringCloud向zookeeper中注册服务 1.引入jar包
2.完成pom文件内容org.springframework.cloud spring-cloud-starter-zookeeper-discovery
3.配置application.yml4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.4 com.example test-zookeeper 0.0.1-SNAPSHOT test-zookeeper Demo project for Spring Boot 1.8 2021.0.1 org.springframework.cloud spring-cloud-starter-zookeeper-discovery org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-actuator org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin
server:
port: 8082
# 服务别名---zookeeper注册中心名称
spring:
application:
name: test-zookeeper
cloud:
zookeeper:
connect-string: 192.168.87.128:2181 #zookeeper地址
max-retries: 10
4.使用@EnableDiscoveryClient注解声明main方法
@SpringBootApplication
@EnableDiscoveryClient
public class TestZookeeperApplication {
public static void main(String[] args) {
SpringApplication.run(TestZookeeperApplication.class, args);
}
}
5.启动服务查看zookeeper中注册的服务
进入容器内容
docker exec -it zookeeper zkCli.sh
查看注册的服务
ls /services
此处注册了三个服务
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
2. 调用接口
@RestController
public class TestController {
//微服务注册名称
private static final String INVOKE_URL = "http://private-cloudzk8002";
@Resource
private RestTemplate restTemplate;
@GetMapping(value = "paymentInfo")
public String paymentInfo(){
//微服务中接口路径
String result = restTemplate.getForObject(INVOKE_URL + "/consumer/payment/zk", String.class);
return result;
}
}
3.请求结果
8082端口返回8002端口的接口信息,调用成功
- 引入jar包,配置zookeeper的配置文件使用@EnableDiscoveryClient注解声明main方法即可成功



