微服务 springCloud学习笔记(六)——向zookeeper中注册服务,并实现调用 - xsi:schemaLocation="
文章目录
一、docker环境下部署zookeeper1.下拉镜像2.部署容器
二、SpringCloud向zookeeper中注册服务1.引入jar包2.完成pom文件内容3.配置application.yml4.使用@EnableDiscoveryClient注解声明main方法5.启动服务查看zookeeper中注册的服务
三、微服务间方法调用1. 声明RestTemplate模板2. 调用接口3.请求结果
总结
一、docker环境下部署zookeeper
1.下拉镜像
docker pull zookeeper
2.部署容器
docker run --privileged=true -d --name zookeeper --publish 2181:2181 -d zookeeper:latest
二、SpringCloud向zookeeper中注册服务
1.引入jar包
org.springframework.cloud
spring-cloud-starter-zookeeper-discovery
2.完成pom文件内容
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.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
3.配置application.yml
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
此处注册了三个服务
三、微服务间方法调用
1. 声明RestTemplate模板
@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方法即可成功
精彩链接