在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所 以需要分布式配置中心组件。在SpringCloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库中。
在spring cloud config 组件中,分两个角色,一是config server,二是config client
Config Server(配置服务器) : 是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件存储
Config Client是Config Server的客户端,用于操作存储在Config Server中的配置内容。 微服务在启动时会请求Config Server获取配置文件的内容,请求到后再启动容器
详细内容看在线文档 : https://www.springcloud.cc/spring-cloud-config.html

- 分割,我这里是 base-dev.yml

单独创建一个微服务,作为配置中心的服务器
pom.xml
<dependencies>
<!-- config 集中配置中心服务器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!--bus 消息总线 作用是创建队列并发消息-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus</artifactId>
</dependency>
<!-- 消息中间件 rabbitMq-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
</dependencies>
application.yml
server:
port: 12000
spring:
application:
name: sunmone-config
cloud:
config:
server:
git:
uri: https://gitee.com/sanpangjwc/xxxxxx.git # gitee 仓库地址
rabbitmq:
host: 192.168.1.1 # rabbitmq 地址
management: # 固定语法,Bus发送消息通知更新的队列地址
endpoints:
web:
exposure:
include: bus-refresh #触发消息总线更新的队列地址 默认访问为: http://127.0.0.1:端口/actuator/bus-refresh
Application 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer // 开启Config服务
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class);
}
}
启动服务浏览器输入: http://localhost:12000/文件名.yml,看到配置文件代表配置成功

客户端就是配置文件被上传到gitee的微服务
添加 pom.xml 依赖
<!--config 集中配置中心客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--消息总线 作用是创建队列并发消息-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus</artifactId>
</dependency>
<!-- 消息中间件 rabbitMq-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
<!--消息总线监听器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
springboot优先识别 bootstrap.yml文件,如果没找到再去找application.yml文件
删除 application.yml 文件,新建 bootstrap.yml 文件

bootstrap.yml
spring: # 添加配置中心服务器地址,Spring就会自动加载配置文件
cloud:
config:
name: base # 配置文件前缀名称 | base-dev.yml
profile: dev # 配置文件后缀名称 | base-dev.yml
label: master # gitee分支名称
uri: http://localhost:12000 # 配置中心服务器的地址

如果我们更新码云中的配置文件,那客户端工程是否可以及时接受新的配置信息呢?我们现在来做一个测试,修改一下码云中的配置文件中mysql的地址,然后测试微服务接口,数据依然没有改变,证明修改服务器中的配置并没有及时更新到工程,只有重新启动程序才会读取配置。
那我们如果想在不重启微服务的情况下更新配置如何来实现呢? 我们使用SpringCloudBus来实现配置的自动更新


POST请求,通知它配置已更新

5. 数据库更改成功,在线更新测试成功