1. 程式人生 > >Spring Cloud Config 入門

Spring Cloud Config 入門

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/

技術分享

填寫好GroupArtifact。選擇依賴的包有Config Server

對應的pom.xml

<dependencies>

<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-config-server</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. 將下載下來的項目導入Eclipse

目錄結構如下,我這裏面新增了bootstrap.yml

技術分享

3. 修改配置

application.yml中添加

server:

port: 8080

bootstrap.yml中添加

spring:

cloud:

config:

server:

git:

uri: https://github.com/DevinXin/config-repo

註意:ConfigServerApplicationSpring 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工程創建一樣,依賴需要webConfig 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 入門