Spring Boot项目整合Spring Cloud Config实现自动配置管理?

在Spring Boot项目中整合Spring Cloud Config可以实现集中化配置管理,帮助开发者将配置从代码中分离出来,而且还可以实现动态更新配置而无需重新部署应用。下面我们就来看看如何实现这个操作。

首先,要实现相关的配置,我们需要创建两个项目Config Server项目用于提供配置的服务。Client Application项目则是使用Spring Cloud Config从Config Server获取配置的客户端应用。如下所示,我们分别来创建两个项目

创建Config Server

Config Server是一个Spring Boot应用,使用Spring Cloud Config Server功能,我们可以创建一个SpringBoot的项目并且添加Config Server相关的配置依赖,接下来就需要在application.yml配置文件中添加ConfigServer配置,这里我们是通过Git来管理配置文件。

server:
  port: 8888

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-repo/config-repo
          searchPaths: folder1, folder2
          clone-on-start: true
  • spring.cloud.config.server.git.uri 指定存放配置文件的Git仓库地址。
  • searchPaths 是你在仓库中配置文件的路径,可以根据需求修改。

启动Config Server

然后,我们需要在主类中添加@EnableConfigServer注解,然后启动应用就可以提供配置服务了,如下所示。

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);
    }
}

运行项目,访问 http://localhost:8888/{application}/{profile},如
http://localhost:8888/application/default
来检查是否能正确获取配置。

创建Client Application

Client Application是业务应用,它将从Config Server获取配置。创建一个SpringBoot的项目然后引入Spring Cloud Config Client依赖,接下来就是在在bootstrap.yml文件中配置Client Application获取配置的方式。如下所示。

spring:
  application:
    name: your-client-app-name

  cloud:
    config:
      uri: http://localhost:8888
      profile: default
      label: master
      discovery:
        enabled: false
  • spring.application.name 应用的名称,对应Config Server上的配置文件名(例如:your-client-app-name-dev.yml)。
  • spring.cloud.config.uri 是Config Server的地址。
  • profile 是指定的环境配置,如dev、prod等。

访问配置

可以在应用中像使用本地配置文件一样使用远程配置文件中的配置值。如下所示。

@Value("${your.property.name}")
private String yourPropertyName;

接下来我们就可以启动应用,从配置文件中获取相关的配置了。

动态刷新配置

为了能够在不重启应用的情况下动态刷新配置,可以借助Spring Cloud Bus和Actuator。

添加依赖

在Client Application的pom.xml文件中添加Spring Cloud Bus依赖,


    org.springframework.cloud
    spring-cloud-starter-bus-amqp

配置消息队列

在application.yml中配置消息队列(如RabbitMQ)的连接信息

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest

启用动态刷新

在Client Application的主类上添加@RefreshScope注解来启用动态刷新,如下所示。

@RefreshScope
@RestController
public class YourController {

    @Value("${your.property.name}")
    private String yourPropertyName;

    @GetMapping("/property")
    public String getProperty() {
        return this.yourPropertyName;
    }
}

触发配置刷新

我们修改了配置之后,我们可以发送一个POST请求到/actuator/bus-refresh来刷新所有客户端的配置,如下所示。

curl -X POST "http://localhost:8080/actuator/bus-refresh"

到这里我们就已经实现了一个Spring Cloud Config Server和一个能够从中获取配置的Spring Boot Client Application,并且还可以通过Spring Cloud Bus实现配置的动态刷新的应用程序。

通过以上步骤,就可以实现Spring Boot项目整合Spring Cloud Config进行自动配置管理。