前言
在分布式系統中,由于服務數量巨多,為了方便服務配置文件統一管理,實時更新,所以需要分布式配置中心組件:spring-cloud-config ,它支持配置服務放在配置服務的內存中(即本地),也支持放在遠程git倉庫中。
本節主要演示怎么用git倉庫作為配置源。
開源地址:https://github.com/bigbeef
創建配置項目
在github中創建一個項目,專門用來保存我們所有項目的配置文件,項目是我的項目結構
配置項目地址:https://github.com/bigbeef/cppba-config
eureka-server.properties
1
2
3
4
5
6
|
eureka.client.register-with-eureka= false eureka.client.fetch-registry= false spring.application.name=eureka-server server.port= 18761 eureka.instance.hostname=peer1 eureka.client.serviceurl.defaultzone=http: //peer1:18761/eureka/ |
創建spring-cloud-config-server項目
項目結構如圖:
pom.xml核心代碼
1
2
3
4
5
6
|
<dependencies> <dependency> <groupid>org.springframework.cloud</groupid> <artifactid>spring-cloud-config-server</artifactid> </dependency> </dependencies> |
springcloudconfigserverapplication.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package com.cppba; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.cloud.config.server.enableconfigserver; @springbootapplication @enableconfigserver public class springcloudconfigserverapplication { public static void main(string[] args) { springapplication.run(springcloudconfigserverapplication. class , args); } } |
application.properties
這個根據自己實際的git項目修改配置
1
2
3
4
5
6
7
8
9
10
11
12
|
server.port= 8888 spring.application.name=config-server spring.cloud.config.server.git.uri=https: //github.com/bigbeef/cppba-config spring.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就簡單搭起來,后面的章節我會教大家怎么在項目中讀取配置
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/6d51157d22ed