在微服務系統中,服務較多,相同的配置:如數據庫信息、緩存、參數等,會出如今不一樣的服務上,若是一個配置發生變化,須要修改不少的服務配置。spring cloud提供配置中心,來解決這個場景問題。
系統中的通用配置存儲在相同的地址:GitHub,Gitee,本地配置服務等,而後配置中心讀取配置以restful發佈出來,其它服務能夠調用接口獲取配置信息。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
這裏注意讀取文件的配置node
server: port: 9001 spring: application: name: config-server-9001 profiles: # 讀取本地 # active: native # 讀取Git active: git cloud: config: server: native: search-locations: classpath:/config git: # 讀取的倉庫地址 uri: https://gitee.com/cicadasmile/spring-cloud-config.git # 讀取倉庫指定文件夾下 search-paths: /cloudbaseconfig # 非公開須要的登陸帳號 username: password: label: master
不一樣的環境讀取的結果不一樣。git
info: date: 20190814 author: cicada sign: develop version: V1.0
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
在上面的配置中心,配置讀取Git資源,因此這裏的配置也就是讀取Git資源。github
server: port: 8001 spring: application: name: config-client-8001 profiles: active: dev cloud: config: # 讀取本地配置 --------------------------- #uri: http://localhost:9001 ## 讀取策略:快速失敗 #fail-fast: true ## 讀取的文件名:無後綴 #name: client-8001 ## 讀取的配置環境 #profile: dev # client-8001-dev.yml # ---------------------------------------- # github上的資源名稱 ----------------------- name: client-8001 # 讀取的配置環境 profile: dev label: master # 本微服務啓動後,經過配置中心6001服務,獲取GitHub的配置文件 uri: http://localhost:9001 # ----------------------------------------
@RestController public class ClientController { @Value("${info.date}") private String date ; @Value("${info.author}") private String author ; @Value("${info.sign}") private String sign ; @Value("${info.version}") private String version ; /** * 獲取配置信息 */ @RequestMapping("/getConfigInfo") public String getConfigInfo (){ return date+"-"+author+"-"+sign+"-"+version ; } }
上面的模式,經過服務中心,直接獲取配置。下面把註冊中心Eureka加進來。spring
啓動順序也是以下:數據庫
node06-eureka-7001 config-server-9001 config-client-8001
完成後Eureka註冊中心效果圖,啓動順序以下:segmentfault
經過註冊中心獲取服務,避免使用URI地址。緩存
通過測試後,正確無誤。restful
GitHub地址:知了一笑 https://github.com/cicadasmile/spring-cloud-base 碼雲地址:知了一笑 https://gitee.com/cicadasmile/spring-cloud-base