MST

星途 面试题库

面试题:微服务架构下开源配置中心工具的基本使用

在微服务架构中,常用的开源配置中心工具如Spring Cloud Config有哪些核心组件?请简述如何使用它为微服务配置不同环境(开发、测试、生产)的配置文件。
22.1万 热度难度
后端开发微服务架构

知识考点

AI 面试

面试题答案

一键面试

Spring Cloud Config核心组件

  1. Config Server:负责存储配置文件,并为客户端提供配置数据的访问接口。它可以从本地文件系统、Git仓库、SVN等多种数据源获取配置文件。
  2. Config Client:微服务应用中的组件,用于从Config Server获取配置数据,并在应用启动时加载这些配置。它会根据应用的名称、环境(如开发、测试、生产)等信息向Config Server请求对应的配置。

使用Spring Cloud Config为微服务配置不同环境的配置文件步骤

  1. 搭建Config Server
    • 引入依赖:在Spring Boot项目的pom.xml中添加Spring Cloud Config Server相关依赖,例如:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
- **配置数据源**:如果使用Git作为配置文件存储,在`application.properties`或`application.yml`中配置Git仓库地址,例如:
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-repo/config-repo
- **启用Config Server**:在主应用类上添加`@EnableConfigServer`注解。

2. 创建配置文件: - 在Git仓库中,按照约定的命名规则创建配置文件。例如,对于名为example-service的微服务,在开发环境的配置文件命名为example-service -dev.propertiesexample-service -dev.yml;测试环境为example-service -test.propertiesexample-service -test.yml;生产环境为example-service -prod.propertiesexample-service -prod.yml。 3. 配置微服务(Config Client): - 引入依赖:在微服务的pom.xml中添加Spring Cloud Config Client依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
- **配置连接Config Server**:在微服务的`bootstrap.properties`或`bootstrap.yml`中配置连接Config Server的信息,例如:
spring:
  application:
    name: example-service
  cloud:
    config:
      uri: http://localhost:8888 # Config Server地址
      fail-fast: true # 快速失败,启动时如果无法连接Config Server则报错
      profile: dev # 当前环境,可根据实际替换为test或prod
  1. 加载配置:微服务启动时,Config Client会根据配置向Config Server请求对应环境的配置文件,并加载到应用中供使用。在代码中可以通过@Value注解或Environment对象获取配置值。例如:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExampleController {

    @Value("${example.property}")
    private String exampleProperty;

    @GetMapping("/config")
    public String getConfig() {
        return exampleProperty;
    }
}