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 依賴,像上面一樣配置一下即可