前言
在分布式系統中,由于服務數量巨多,為了方便服務配置文件統一管理,實時更新,所以需要分布式配置中心組件:spring-cloud-config ,它支持配置服務放在配置服務的內存中(即本地),也支持放在遠程Git倉庫中。
本節主要演示怎么用Git倉庫作為配置源。
開源地址:https://github.com/bigbeef
創建配置項目
在github中創建一個項目,專門用來保存我們所有項目的配置文件,項目是我的項目結構
配置項目地址:https://github.com/bigbeef/cppba-config
eureka-server.properties
eureka.client.register-with-eureka=falseeureka.client.fetch-registry=falsespring.application.name=eureka-serverserver.port=18761eureka.instance.hostname=peer1eureka.client.serviceUrl.defaultZone=http://peer1:18761/eureka/
創建spring-cloud-config-server項目
項目結構如圖:
pom.xml核心代碼
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency></dependencies>
SpringCloudConfigServerApplication.java
package com.cppba;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.config.server.EnableConfigServer;@SpringBootApplication@EnableConfigServerpublic class SpringCloudConfigServerApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudConfigServerApplication.class, args); }}
application.properties
這個根據自己實際的git項目修改配置
server.port=8888spring.application.name=config-serverspring.cloud.config.server.git.uri=https://github.com/bigbeef/cppba-configspring.cloud.config.label=master# spring.cloud.config.server.git.username=# spring.cloud.config.server.git.password=spring.cloud.config.server.git.searchPaths=/ cppba-spring-cloud/*,/ cppba-spring-cloud/eureka-client/*
spring.cloud.config.server.git.uri:配置git倉庫地址
spring.cloud.config.server.git.searchPaths:配置倉庫路徑,以逗號隔開
spring.cloud.config.label:配置倉庫的分支
spring.cloud.config.server.git.username:訪問git倉庫的用戶名
spring.cloud.config.server.git.password:訪問git倉庫的用戶密碼
啟動項目
訪問地址:http://127.0.0.1:8888
http請求地址和資源文件映射如下:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
根據我們自己的配置,我們可以這樣訪問:http://127.0.0.1:8888/eureka-server/default/master
application -> eureka-server (應用名)
profile -> default (啟用的配置,通常是后綴,下面解釋)
label -> master (分支)
訪問到的結果就是:
profile比較重要,可以理解成讀取哪些配置文件,假如我不止一個配置文件,可能會有:
eureka-server.properties(這個是通用配置文件,默認都會加載),
eureka-server-mysql.properties,
eureka-server-oracle.properties,
eureka-server-jpa.properties,
eureka-server-mysql.properties......
我們可能會選擇性的加載其中的部分properties配置文件,那我們可以這樣寫:http://127.0.0.1:8888/eureka-server/default,mysql,jpa/master
到此,我們的spring-cloud-config-server就簡單搭起來,后面的章節我會教大家怎么在項目中讀取配置
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選