Spring Cloud 配置中心为分布式系统中的服务器端和客户端提供外部化配置支持。通过Config-Server,你可以在一个地方集中对所有环境中的应用程序的外部化配置进行管理。例如,当一个应用程序从开发环境切换到测试环境,然后再从测试环境切换到生产环境,你可以使用Config-Server统一管理这些环境之间的配置,并确保应用程序在迁移时能够拥有它运行所需要的一切配置。简而言之:Config-Server 就是用来实现配置统一管理和不同环境间配置的统一切换的。Config-Server 服务器的后端存储默认使用Git,因此它很容易支持配置环境的标签版本,同时可供多数的内容管理工具去访问。你也可以很容易地添加其他的替代实现,并将它们插入到Spring配置中。
相关产品:
来自淘宝的Diamond:https://github.com/takeseem/diamond
来自百度的Disconf:https://disconf.readthedocs.io/zh_CN/latest/
来自Springcloud的Config-Server:https://cloud.spring.io/spring-cloud-stream/
搭建配置中心
Config-Server配置中心的工作原理如下图所示:
引入依赖
新建一个maven项目,起名为config-center,在其 pom.xml 文件中引入如下依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
<properties>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<dependencies>
<!-- Eureka-Client 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Config-Server 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!-- SpringCloud 版本控制依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
创建启动类
新建一个Springboot应用的启动类ConfigCenterApplication类,并在上增加@EnableConfigServer注解,用来启用Config-Server。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigCenterApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigCenterApplication.class, args);
}
}
添加配置
application.yml 添加配置如下:
server:
port: 9001
spring:
application:
name: config-center
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
此时,由于尚未配置用来作为服务器后端存储的Git仓库地址,若启动应用会报如下错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Invalid config server configuration.
Action:
If you are using the git profile, you need to set a Git URI in your configuration. If you are using a native profile and have spring.cloud.config.server.bootstrap=true, you need to use a composite configuration.
创建Git仓库
本文使用开源中国的码云来创建我们的Git仓库,当然你也可以选择其他的Github或者阿里云Git等创建自己的Git仓库。
点击导航栏中的“+”按钮==>新建仓库,填入仓库信息,完成创建。
点击 克隆/下载 ==>复制,将Git仓库地址复制下来备用。
配置Git仓库
接下来,在application.yml中添加Git仓库配置如下:
spring:
cloud:
config:
server:
git:
uri: https://gitee.com/pengjunlee/config-cloud.git
username: 你的码云账号
password: 你的账号密码
再次启动ConfigCenterApplication,发现可以正常启动了。启动完成之后,Eureka注册中心中注册的服务列表如下: