SpringCloud Config
統一配置中心學習筆記
在分佈式系統中,由於服務數量巨多,爲了方便服務配置文件統一管理,實時更新,所以需要分佈式配置中心組件。在Spring Cloud中,有分佈式配置中心組件spring cloud config ,它支持配置服務放在配置服務的內存中(即本地),也支持放在遠程Git倉庫中。在spring cloud config 組件中,分兩個角色,一是config server,二是config client。
Config Server是一個可橫向擴展、集中式的配置服務器,它用於集中管理應用程序各個環境下的配置,默認使用Git存儲配置文件內容,也可以使用SVN存儲,或者是本地文件存儲。
Config Client是Config Server的客戶端,用於操作存儲在Config Server中的配置內容。微服務在啓動時會請求Config Server獲取配置文件的內容,請求到後再啓動容器。
使用的理由:
1.不方便維護
多人同時對配置文件進行修改,衝突不斷,很難維護
2.配置內容安全和權限
主要是針對線上的配置來說,一般不對開發公開,只有運維有權限所以需要將配置文件隔離,不放到項目代碼裏
3.更新配置項目需要重啓
每次更新配置文件都需要重啓項目,很耗時。使用了配置中心後,即可實現配置實時更新(需配合springcloud-BUS)
配置服務端:
1. 將配置文件提交到碼雲
- 上傳配置文件,將
eureka_service
模塊的application.yml
改名爲eurekaService-dev.yml
後上傳
上傳成功後可以在線修改或者等等操作;
文件命名規則:
{application}-{profile}.yml或{application}-{profile}.properties
application爲應用名稱 profile指的開發環境(用於區分開發環境,測試環境、生產環境等)
2. 創建模塊 demo-config
並引入依賴:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
3. 創建包和啓動類: 並加上 @EnableConfigServer 註解,開啓配置服務
@SpringBootApplication
@EnableConfigServer //開啓配置服務
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
4. 編寫配置文件application.yml
spring:
application:
name: demo-config
cloud:
config:
server:
git:
uri: https://gitee.com/chuanzhiliubei/tensquare-config.git
#username: xxx 私有倉庫需配
#password: xxx
server:
port: 12000
5.啓動模塊 訪問http://localhost:12000/eurekaService-dev.yml 可以看到配置文件內容爲配置成功
配置客戶端:
1. 在eureka_service模塊上添加依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2. 添加bootstrap.yml
(名稱固定值) ,刪除application.yml
spring:
cloud:
config:
name: service #name和雲端名稱有關name+profile=配置文件名稱: 例如:碼雲的文件名爲service-dev.yml
profile: dev
label: master #拿雲端上的那個分支
uri: http://127.0.0.1:12000 #集中式配置工程地址(demo-config模塊的地址)
3. 啓動工程模塊demo-config
和 eureka_service
看看eureka_service
模塊是否正常啓動(如果正常啓動並能訪問到管理界面說明配置成功)
擴展資料:
配合rabbitMQ和springcloud-BUS 實現不用重啓更新配置文件生效: https://segmentfault.com/a/1190000018910010