一.Config概述
Spring Cloud Config 提供一种基于客户端与服务端(C/S)模式的分布式的配置管理。我们可以把我们的配置管理在我们的应用之外(config server 端),并且可以在外部对配置进行不同环境的管理,比如开发/测试/生产环境隔离,并且还能够做到实时更新配置。
二.服务搭建
配置中心服务搭建好以后,我们主要有两种方式实现配置的读取,一种是本地模式,一种是远程模式。本地模式即在本地读取配置文件,远程我们可以通过,github或者gitlap、gitee等项目工具管理配置文件。
首先,我们先介绍本地拉取配置文件服务端配置。
- 服务端依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
- 服务端配置
server:
port: 8084
spring:
application:
name: qyconfigserver
profiles:
active: native
cloud:
config:
server:
native:
searchLocations: classpath:/config
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
- 服务端启动类以及关键注解
@Slf4j
@RefreshScope
@EnableConfigServer
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
public class ConfigServerApplication
{
public static void main( String[] args )
{
SpringApplication.run(ConfigServerApplication.class, args);
log.info("配置中心启动成功!");
}
}
- 项目结构
其次,我们还要搭建客户端来调用服务端配置。客户端没有数据库连接的配置文件,我将数据库配置文件放在本地配置中心管理。下面我们来试试用之前的模块集成config客户端能不能正常的从本地配置中心拉取数据库连接配置。
客户端我以我之前搭建的集成mybatisplus服务为客户端,拿现成的不要太香。
- 客户端依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
- 客户端配置文件
spring:
application:
name: qymybatisplusclient
cloud:
config:
uri: http://localhost:8084/
# label: master
failFast: true
# 本地配置文件访问
profile: gr
retry:
initial-interval: 2000
max-interval: 2000
max-attempts: 2000
multiplier: 1.2
- 客户端启动类
@Slf4j
@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages = {"org.qy.mybatisplus.client"})
public class MybatisplusApplication
{
public static void main( String[] args )
{
ApplicationContext context = SpringApplication.run(MybatisplusApplication.class, args);
String serverPort = context.getEnvironment().getProperty("server.port");
log.info("后台管理服务客户端启动成功! Swagger2: http://127.0.0.1:".concat(serverPort).concat("/swagger-ui.html"));
}
}
最后,我们就这样很快速的搭建好本地配置中心的配置管理。我们来访问一下能不能正常读取数据库数据。
三.配置文件名与URL的映射关系
Config Server 中配置文件的 HTTP 资源操作方式如下
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
其中,{application} 被用于 spring 配置的配置文件名称,在 spring boot 中通常默认为 application;{profile} 表示激活的配置文件,通常用于区分开发/测试/生产环境;{label} 则表示 git 的分支,默认为 master。
这样我们就做到了配置中心的本地化管理。下一章节,我们来配置远程拉取配置文件。