Spring Cloud Config工作原理
- 服务端与客户端架构
Spring Cloud Config采用客户端 - 服务端架构。Config Server作为服务端,负责存储和提供配置文件,支持多种后端存储方式,如Git、SVN、本地文件系统等。微服务作为客户端,向Config Server请求获取配置信息。
- 配置读取流程
- 客户端启动时,会根据配置的Config Server地址,向服务端发送请求,请求格式通常包含应用名称、环境(如dev、prod等)和标签(如master分支等)。
- Config Server根据请求参数,从配置存储后端查找对应的配置文件,并返回给客户端。
- 配置版本控制
使用Git等版本控制系统时,Config Server可以方便地管理配置的版本历史,追踪配置的变更记录,方便回滚到特定版本的配置。
使用Spring Cloud Config集中管理微服务配置
- 搭建Config Server
- 引入依赖:在Maven项目中,在
pom.xml
文件引入spring - cloud - starter - config - server
依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring - cloud - starter - config - server</artifactId>
</dependency>
- 配置Server:在
application.yml
文件中配置后端存储,例如使用Git:
spring:
cloud:
config:
server:
git:
uri: https://github.com/your - repo/config - repo
search - paths: '{application}'
- 启动Server:通过
@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 ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
- 配置客户端
- 引入依赖:在客户端项目的
pom.xml
中引入spring - cloud - starter - config
依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring - cloud - starter - config</artifactId>
</dependency>
- bootstrap配置:在
bootstrap.properties
或bootstrap.yml
文件中配置Config Server地址和应用相关信息。
spring:
application:
name: your - application - name
cloud:
config:
uri: http://localhost:8888
fail - fast: true
- 获取配置:启动客户端后,Spring会自动从Config Server获取配置,并注入到应用的
Environment
中,通过@Value
注解或Environment
对象即可获取配置值。
配置更新时微服务的动态刷新
- 引入动态刷新依赖
在客户端项目的
pom.xml
中引入spring - cloud - starter - bus - actuator
依赖,该依赖集成了Spring Cloud Bus和Spring Boot Actuator。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring - cloud - starter - bus - actuator</artifactId>
</dependency>
- 配置动态刷新
- 在
application.yml
文件中启用Actuator的/refresh
端点,并配置Spring Cloud Bus相关信息,例如使用RabbitMQ:
management:
endpoints:
web:
exposure:
include: refresh
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
- 触发动态刷新
- 手动触发:通过发送POST请求到
/actuator/refresh
端点来触发单个微服务的配置刷新。例如使用curl
命令:curl -X POST http://localhost:8080/actuator/refresh
。
- 自动广播:结合Spring Cloud Bus,当Config Server中的配置发生变化时,可以通过消息总线(如RabbitMQ、Kafka)广播配置更新事件,所有监听该事件的微服务客户端会自动刷新配置。可以通过向
/actuator/bus - refresh
端点发送POST请求来触发广播。例如curl -X POST http://localhost:8080/actuator/bus - refresh
。同时,也可以指定特定服务进行刷新,如curl -X POST http://localhost:8080/actuator/bus - refresh/{destination}
,{destination}
为具体服务名称或服务实例。