面试题答案
一键面试Spring Cloud Config核心组件
- Config Server:负责存储配置文件,并为客户端提供配置数据的访问接口。它可以从本地文件系统、Git仓库、SVN等多种数据源获取配置文件。
- Config Client:微服务应用中的组件,用于从Config Server获取配置数据,并在应用启动时加载这些配置。它会根据应用的名称、环境(如开发、测试、生产)等信息向Config Server请求对应的配置。
使用Spring Cloud Config为微服务配置不同环境的配置文件步骤
- 搭建Config Server:
- 引入依赖:在Spring Boot项目的
pom.xml
中添加Spring Cloud Config Server相关依赖,例如:
- 引入依赖:在Spring Boot项目的
<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.properties
或example-service -dev.yml
;测试环境为example-service -test.properties
或example-service -test.yml
;生产环境为example-service -prod.properties
或example-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
- 加载配置:微服务启动时,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;
}
}