Spring Cloud 進階之路 -- 統一配置中心 Config Client 端配置
Spring Cloud 統一配置中心 - Config Client 搭建步驟:
1、引入依賴
2、application.yml 改為 bootstrap.yml
3、增加spring.cloud.config 相關配置,去掉已提交到git的配置
4、測試去掉的配置是否能從git 成功拉取
具體如下:
1、引入依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-client</artifactId> </dependency>
2、application.yml 改為 bootstrap.yml
bootstrap.yml(或bootstrap.properties)在程式引導時執行,應用於更早期的配置資訊讀取,bootstrap.yml 先於 application.yml 載入,因為把資料庫連線資訊放入了gitee,如果依舊用 application.yml,啟動時會報如下錯:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class
所以需要將application.yml 改為 bootstrap.yml,應用啟動時,配置資訊首先從 config server 載入,取得資料庫配置等資訊,這裡就是提前要拿到的引導配置,用來載入真正需要的配置資訊。
改完後啟動,看下日誌,看到 :Fetching config from server at : http://localhost:8080/ 如下圖:
3、增加spring.cloud.config 相關配置,去掉已提交到git的配置
這裡主要增加:
cloud: config: discovery: enabled: true # 對應註冊到Eureka中的配置中心應用名 service-id: CONFIG profile: dev
完全配置:
spring:
application:
name: order
cloud:
config:
discovery:
enabled: true
# 對應註冊到Eureka中的配置中心應用名
service-id: CONFIG
profile: dev
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
server:
port: 8091
已將資料庫配置移到git上。
4、測試去掉的配置是否能從git 成功拉取
程式啟動成功說明資料庫沒有問題,另測試了一下是否能獲取到git上的配置,上圖分別表示:
(1)、service-id對應配置中心應用名
(2)、通過應用名order拼上profile找到配置檔案
(3)、測試是否能獲取到env
(4)、訪問後得到 dev 測試通過,配置成功
另外注意:Eureka 的配置如果放到git上,又不是預設埠的話,就會有問題,載入不到,是因為客戶端需要先Eureka 的地址,再通過 Eureka 裡的應用名找到配置中心,然後才能通過配置中心去讀取配置,如果Eureka 都沒有拿到,何談CONFIG。