1. 为什么要用配置中心和消息总线
在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库中。在spring cloud config 组件中,分两个角色,一是config server,二是config client。
Config Server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储,或者是本地文件存储。
Config Client是Config Server的客户端,用于操作存储在Config Server中的配置内容。微服务在启动时会请求Config Server获取配置文件的内容,请求到后再启动容器。
消息总线。简单理解就是一个消息中心,众多微服务实例可以连接到总线上,实例可以往消息中心发送或接收信息(通过监听),用它结合配置中心,能够实现不重启服务的情况下,刷新配置文件,具体实现如下:
- 配置文件放置云端
- 服务端引入依赖,添加配置,暴露服务,自动放置mq队列
- 启动服务端,查看mq队列情况,验证能否获取到云端配置信息
- 客户端引入依赖,添加配置, 自动放置mq队列
- 请求/actuator/bus-refresh 手动刷新配置
2. 实践步骤
2.1 将配置文件提交至码云
如图所示:
文件命名规则:{application}-{profile}.yml或{application}-{profile}.properties
2.2 配置服务端
配置中心pom.xml配置如下:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
</dependencies>
配置rabbitmq和bus
server:
port: 12000
spring:
application:
name: yixin-config
cloud:
config:
server:
git:
uri: https://gitee.com/GTAV/yixin-dev.git
rabbitmq:
host: localhost
management:
endpoints:
web:
exposure:
include: bus-refresh
配置中心添加注解开始配置服务
@EnableConfigServer
然后启动服务,访问http://localhost:12000/base-dev.yml ,看到如图的配置文件信息
访问http://localhost:15672,Queues多了个队列
2.3 配置客户端
引入依赖
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus</artifactId>
</dependency>
<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>
在客户端配置文件中加上mq配置
rabbitmq:
host: 192.168.184.135
配置完成后,启动服务
访问http://localhost:15672,查看rabbitmq管理台,此时的Queues应该有2个
修改码云上的配置文件后,使用postman测试 Url: http://127.0.0.1:12000/actuator/bus-refresh Method:post
然后访问:http://localhost:12000/user-dev.yml 观察配置文件是否刷新