在微服务架构中,配置的统一管理与动态更新变得尤为重要。Spring Cloud Config Server 提供了一种集中式的配置管理方案,允许微服务在运行时动态地拉取配置信息。本文将详细介绍如何搭建和使用 Spring Cloud Config Server,以及如何让 Spring Boot 应用作为 Config Client 来消费这些配置。
项目源码见最下方
一、搭建 Spring Cloud Config Server
1.1 创建 Maven 项目
使用 Spring Initializr 创建一个新的 Maven 项目,添加以下依赖:
- spring-boot-starter-web
- spring-cloud-config-server
1.2 配置 application.yml
在项目的src/main/resources
目录下,创建application.yml
文件,配置 Config Server 的源:
Yaml
深色版本
1spring:
2 cloud:
3 config:
4 server:
5 git:
6 uri: https://github.com/your-organization/your-repo.git
7 default-label: main
8 search-paths: config
9 username: your-username
10 password: your-password
11server:
12 port: 8888
这里假设你已经在 GitHub 上创建了一个名为your-repo
的仓库,其中包含了配置文件。search-paths
参数指定了配置文件的路径,default-label
指定了默认分支。
1.3 启动 Config Server
运行你的 Spring Boot 应用,Config Server 就会在端口 8888 上启动。
二、创建配置文件
在你的 GitHub 仓库的config
目录下,为每个微服务创建配置文件。例如,为service-a
创建service-a-dev.yml
和service-a-prod.yml
文件。
Yaml
深色版本
1# service-a-dev.yml
2server:
3 port: 8080
4
5spring:
6 profiles:
7 active: dev
8
9# service-a-prod.yml
10server:
11 port: 8081
12
13spring:
14 profiles:
15 active: prod
三、搭建 Spring Cloud Config Client
3.1 添加依赖
在 Spring Boot 项目的pom.xml
中添加以下依赖:
Xml
深色版本
1<dependency>
2 <groupId>org.springframework.cloud</groupId>
3 <artifactId>spring-cloud-starter-config</artifactId>
4</dependency>
3.2 配置 application.yml
配置 Spring Cloud Config Client 的信息:
Yaml
深色版本
1spring:
2 application:
3 name: service-a
4 cloud:
5 config:
6 uri: http://localhost:8888
7 profile: dev
8 label: main
9 fail-fast: true
10 retry:
11 initial-interval: 1000
12 max-attempts: 30
13 multiplier: 1.1
14 timeout: 5000
这里指定了 Config Server 的 URL、微服务的名称、环境配置文件的标签、以及配置重试策略。
3.3 使用配置
在你的 Spring Boot 应用中,你可以像往常一样使用@Value
注解或通过Environment
和ConfigurableEnvironment
来访问配置:
Java
深色版本
1import org.springframework.beans.factory.annotation.Value;
2import org.springframework.web.bind.annotation.GetMapping;
3import org.springframework.web.bind.annotation.RestController;
4
5@RestController
6public class MyController {
7
8 @Value("${server.port}")
9 private String port;
10
11 @GetMapping("/port")
12 public String getPort() {
13 return "Running on port: " + port;
14 }
15}
3.4 部署和测试
部署你的 Spring Boot 应用,访问http://localhost:8080/port
,你应该能看到正确的端口号,这证明你的应用已经成功从 Config Server 获取到了配置。
四、动态刷新配置
为了使应用能够实时响应配置变化,你需要在你的应用中添加以下依赖:
Xml
深色版本
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-actuator</artifactId>
4</dependency>
然后在application.yml
中启用refresh
端点:
Yaml
深色版本
1management:
2 endpoints:
3 web:
4 exposure:
5 include: refresh
现在,你可以在 Config Server 上修改配置文件,并通过发送 POST 请求到http://localhost:8080/actuator/refresh
来刷新你的应用配置。
五、总结
Spring Cloud Config Server 和 Client 提供了一个统一的、动态的配置管理方案,极大地简化了微服务架构中配置的管理。通过本文的实践,你应该已经能够搭建和使用 Spring Cloud Config,为你的微服务应用提供更加强大和灵活的配置管理能力。
项目源码下载地址:https://download.csdn.net/download/qq_42072014/89535131