Spring Cloud Config 使用指南
Spring Cloud Config 是一个强大的分布式配置中心,用于集中管理微服务架构中的配置信息。它支持多种配置源,如 Git、本地文件系统、数据库等,并提供配置的动态刷新功能。本文将详细介绍如何搭建和使用 Spring Cloud Config。
一、搭建配置中心(Config Server)
1. 创建 Config Server 项目
使用 Spring Initializr 创建一个 Spring Boot 项目,添加以下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
2. 启用 Config Server
在项目的主类上添加 @EnableConfigServer
注解:
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
3. 配置 Git 仓库
在 application.yml
或 application.properties
文件中配置 Git 仓库地址:
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/your-repo/config-repo.git
search-paths: '{application}' # 按应用名查找目录
label: master # 默认分支
4. 启动 Config Server
运行项目后,访问 http://localhost:8888/{application}/{profile}
,例如:
curl http://localhost:8888/config/dev
这将返回对应应用和环境的配置信息。
二、配置客户端(Config Client)
1. 添加依赖
在客户端项目中添加以下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2. 配置客户端
在客户端项目的 bootstrap.yml
文件中配置 Config Server 的地址和环境:
spring:
application:
name: config-client
cloud:
config:
uri: http://localhost:8888
profile: dev
label: master
bootstrap.yml
的加载优先级高于 application.yml
,因此适合用于加载外部配置。
3. 使用配置
在客户端项目中,可以直接通过 @Value
或 @ConfigurationProperties
注解使用配置中心的配置信息。例如:
@RestController
public class ConfigClientController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/config")
public String getConfig() {
return configInfo;
}
}
三、核心功能
1. 配置文件的命名规则
Spring Cloud Config 支持以下几种资源路径:
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}/{profile}[/{label}]
例如:
http://localhost:8888/config-client/dev
:获取config-client-dev.yml
文件的配置。http://localhost:8888/master/config-client-dev.yml
:指定分支master
。
2. 配置加密与安全
为了保护敏感信息,Spring Cloud Config 支持加密配置:
- 配置加密密钥:
encrypt: key: my-secret-key
- 加密数据:
curl http://localhost:8888/encrypt -d "secret123"
- 使用密文:
datasource: password: '{cipher}密文字符串'
3. 动态配置刷新
客户端可以通过调用 /actuator/refresh
端点来刷新配置:
- 添加 Actuator 依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
- 暴露
refresh
端点:management: endpoints: web: exposure: include: refresh
- 调用刷新接口:
POST http://localhost:8080/actuator/refresh
四、多环境支持
Spring Cloud Config 支持多环境配置,通过 spring.profiles.active
指定环境。例如:
config-client-dev.yml
:开发环境配置config-client-prod.yml
:生产环境配置
客户端可以通过设置 spring.profiles.active
来加载对应环境的配置。
五、总结
Spring Cloud Config 提供了一个集中化的配置管理解决方案,支持多种配置源、动态刷新和多环境配置。通过简单的配置和依赖添加,即可快速搭建配置中心和客户端。它不仅简化了配置管理的复杂性,还提高了系统的灵活性和可维护性。
希望本文能帮助你快速掌握 Spring Cloud Config 的使用方法,为你的微服务架构开发提供有力支持。