Config Client
一、基本搭建
1 .首先创建一个 Spring Boot 项目作为 module ,项目名为config-client
依赖需要添加 Web、Config Client 依赖
项目创建完成
2.项目创建成功后,再 resources 目录添加 bootstraps.properties 资源文件
配置 bootstraps.properties
# 下面三行配置分别对应 config-server 中的{application}、{profile}、{label}占位符
spring.application.name=client1
spring.cloud.config.label=master
spring.cloud.config.profile=dev
spring.cloud.config.uri=http://localhost:8081
server.port=8082
前三行配置就是Spring Cloud 学习笔记 ——Spring Cloud Config 的 Server端搭建中提到的如下内容相对应:
访问 Git 上的配置文件接口名:
- 1./{application}/{profile}/{label}
- 2./{application}-{profile}.yml
- 3./{application}-{profile}.properties
- 4./{label}/{application}-{profile}.properties
- 5./{label}/{application}-{profile}.yml
application 表示配置文件名
profile 表示配置文件的 profile,例如 test、dev、prod,与 SpringBoot 切换配置文件的 profile 是一样的
label表示git 的分支,参数可选,默认就是 master
spring.cloud.config.uri
是 config-server 的服务地址;这里假设我们已经有了 Git 上 client1-dev.properties 中的内容,写一个接口测试一下;
- 3 编写接口
@RestController
@RefreshScope
public class HelloController {
@Value("${javaboy}")
String javaboy;
@GetMapping("/hello")
public String hello(){
return javaboy;
}
}
-
4 ,启动 config-server 服务 和 client1 服务(config-client)
-
启动成功后访问:
http://localhost:8082/hello
接口
请求成功,访问的内容就是 git 上的 client1-dev.properties;其实是再 client1 项目启动时访问 Config Server 获取的,这就是 Config Client 的使用;
如果有其他微服务也要连接 Config Server ,只需要添加 Config Client 依赖,像上面一样配置一下即可