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>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

注意: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中获取到配置文件中的值。