Spring Cloud Config 入門
1. 簡介
Spring Cloud Config 是用來為分布式系統中為微服務應用提供集中化的外部配置支持,主要分為Spring Cloud Config Server(服務器端)和Spring Cloud Config Client(客戶端)。
2. Spring Cloud Config Server
Spring Cloud Config Server為服務器端,它是一個單獨的微服務應用,用來連接配置倉庫(本文使用的是git倉庫)並為客戶端獲取配置信息。
1. 首先,創建config server工程
打開http://start.spring.io/
填寫好Group、Artifact。選擇依賴的包有Config Server。
對應的pom.xml為
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
2. 將下載下來的項目導入Eclipse。
目錄結構如下,我這裏面新增了bootstrap.yml
3. 修改配置
在application.yml中添加
server:
port: 8080
在bootstrap.yml中添加
spring:
cloud:
config:
server:
git:
uri: https://github.com/DevinXin/config-repo
註意:ConfigServerApplication,Spring Boot 啟動類上需要添加@EnableConfigServer註解
4. 啟動configServer
通過訪問http://localhost:8080/master/foobar-dev.properties可以讀到git上的配置文件。
3. Spring Cloud Config Client
Spring Cloud Config Client為客戶端,客戶端通過配置連接服務器端,從服務器端加載配置信息。
1. 創建config client工程
同config server工程創建一樣,依賴需要web,Config Client
對應的pom.xml為:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2. 修改配置
application.yml配置為
server:
port: 8081
bootstrap.yml配置為
spring:
cloud:
config:
uri: http://localhost:8080/
profile: dev
label: master
application:
name: foobar
3. 寫一個Controller
4. 啟動config Client。
訪問http://localhost:8081/configServer
可以從config Server中獲取到配置文件中的值。
本文出自 “辛立光博客” 博客,請務必保留此出處http://devinxin.blog.51cto.com/2325562/1939372
Spring Cloud Config 入門