SpringCloud分佈式(五)分佈式統一配置Config使用詳解

在分佈式系統中,配置儘可能的不放到每個項目的配置文件中,因爲這樣改動起來很麻煩,而是放到一個集中的配置服務器上。舉例子:在數據庫中搞一個T_Configs表。
Spring cloud Config是一個用Git進行配置信息存儲的配置服務器,各個應用可以從他裏面加載配置。

首先要配置git服務器。當然也可以使用公共的git服務器,下面演示使用現成的git服務器
創建ConfigServer:創建Spring Starter項目,勾選ConfigServer。XXXApplication上標註@EnableConfigServer。

application.properties文件配置以下
spring.application.name=config-server
server.port=8888
spring.cloud.config.server.git.uri=https://github.com/forezp/SpringcloudConfig/
spring.cloud.config.server.git.searchPaths=respo
spring.cloud.config.label=master

如果讀取git還需要用戶密碼的話,那就還要配置spring.cloud.config.server.git.username、spring.cloud.config.server.git.password

spring.cloud.config.server.git.searchPaths=respo表示從respo中找到匹配的內容。
3、創建Config讀取使用者。比如創建一個Web項目,並且勾選ConfigClient
在application.properties中配置
spring.application.name=config-client
spring.cloud.config.label=master
spring.cloud.config.profile=dev
spring.cloud.config.uri= http://localhost:8888/
server.port=10010

會讀取和自己應用名字一樣的配置文件下的內容,也就是配置文件的文件名要和使用者的“spring.application.name”一致。

其中spring.cloud.config.profile表示讀取哪個profile的文件。spring.cloud.config.uri表示Config服務器地址

4、使用@Value讀取配置中名字爲foo的內容。

@RestController
@RequestMapping("/main")
public class MainController {
	
	@Value("${foo}")
	String foo;
	
	@RequestMapping("/test1")
	public String test1()
	{
		return foo;
	}
}

我在開源項目中也使用到了類似的配置可以參考:
跳轉

https://github.com/RAOE/Cloud_Ixu

https://github.com/RAOE/show-videos

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章