面试题答案
一键面试Spring Cloud Config工作原理
- 服务器端:Spring Cloud Config Server是一个中心化的外部配置服务器,它负责从不同的配置源(如Git、SVN、本地文件系统等)加载配置文件,并通过REST接口提供给各个微服务。
- 客户端:微服务作为Config Client,启动时会向Config Server发送请求,获取对应环境(如dev、prod等)和应用名的配置信息。Config Client通过HTTP/HTTPS协议与Config Server通信,将获取到的配置信息整合到自身的Spring Environment中,就像本地配置一样使用。
使用场景
- 多环境配置管理:不同环境(开发、测试、生产)可能有不同的数据库连接、缓存配置等,通过Spring Cloud Config可以集中管理这些不同环境的配置,方便切换和维护。
- 微服务配置统一管理:在微服务架构中,众多微服务的配置可以统一放在Config Server中,避免每个微服务单独管理配置文件,提高配置的一致性和可维护性。
配置动态更新实现
- 引入依赖:在微服务的
pom.xml
中添加Spring Cloud Bus和Spring Cloud Config的相关依赖,如:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
- 配置文件:在
bootstrap.properties
中配置连接Config Server的信息,如:
spring.application.name=your - service - name
spring.cloud.config.uri=http://config - server - address:port
spring.cloud.config.fail - fast=true
- 开启刷新功能:在主应用类或配置类上添加
@RefreshScope
注解,使配置能够动态刷新。例如:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
@SpringBootApplication
@RefreshScope
public class YourServiceApplication {
public static void main(String[] args) {
SpringApplication.run(YourServiceApplication.class, args);
}
}
- 触发更新:当配置在Config Server(如Git仓库)中发生变化时,可以通过发送POST请求到
/actuator/bus - refresh
端点来触发所有微服务的配置更新。如果只想更新某个特定微服务,可以指定微服务名称,如/actuator/bus - refresh/{destination:your - service - name}
。这里假设使用Spring Boot Actuator,并且配置了相应的权限等。例如使用curl命令:
curl -X POST http://your - service - address:port/actuator/bus - refresh
这样,微服务无需重启就能获取到新的配置。