一、概述
Spring Cloud Config为分布式系统中的外部化配置提供服务器端和客户端支持。使用Config Server,可以在中心位置管理所有环境中应用程序的外部属性。Config Server默认使用Git作为配置存储的后端,但也可以支持其他存储方式如SVN、本地文件系统、MySQL等。
本文将介绍 Spring Cloud Config与gitlab完成搭建配置中心,并提供client端刷新机制。用到的技术或框架版本如下:jdk1.8 (java8) 、spring-boot 2.7、spring cloud config、spring actuator、gitlab。(本文中讲述的代码完整源码见:项目源码地址 )
二、项目架构
三、 配置与搭建
3.1 Spring cloud config 服务端搭建
Step1: 添加依赖jar
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
Step2: 配置git 地址与密码、分支等
server:
port: 8888
spring:
profiles:
active: dev
cloud:
config:
server:
git:
uri: http://xxxxx.git
password: xxxxx
search-paths: config
default-label: master
clone-on-start: true
Step3: 添加spring config server启动注解
@SpringBootApplication
@EnableConfigServer
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
}
3.2 Spring cloud config 客户端使用配置
Step1: 添加依赖jar
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Step2: 配置spring-config服务端与spring-config刷新配置
server:
port: 8080
spring:
profiles:
active: dev
application:
name: application
config:
import: "optional:configserver:http://localhost:8888"
# 暴露刷新接口
management:
endpoints:
web:
exposure:
include: refresh
Step3: 配置类使用
在配置类中添加 @RefreshScope注解标注哪些配置需要刷新
@Component
@RefreshScope
public class TestConfig {
@Value("${config.value}")
private String configValue;
public String getConfigValue() {
return configValue;
}
}
3.3 Gitlab仓库配置文件
在git 仓库中建一个目录config,然后再config下建一个文件名称为 application-dev.yml
3.4 运行测试
- 获取配置
-
使用actuator暴露的接口刷新配置
curl -X 'POST' 'http://127.0.0.1:8080/actuator/refresh'
四、 结束语
项目github地址:见链接。如有前后端技术问题,欢迎一起交流!