此文章仅写给自己及同事探讨使用,不可作为教程学习
为什么需要分布式配置中心:
分布式系统中,服务数量太多,为了方便服务配置文件的统一管理,所以我们需要分布式配置中心组件。
在没有使用配置中心时:
1,配置文件分散在各个项目里,不方便维护
2,配置文件的权限与安全得不到保障
3,配置文件更新,项目需要重启
POM:
添加依赖:<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
模块配置文件:(bootstrap.yml)
spring:
application:
#应用名,需要保持与服务器中需要读取的配置名一致,如服务器中此配置文件名为test-config-#dev.properties,去除dev(表示环境为dev)及后缀
name: test-config
cloud:
config:
uri: http://localhost:9001/ #config server的uri
profile: dev #指定环境
label: master #指定分支
server:
port:9201
配置文件手动刷新:
/refresh:
添加spring-boot-starter-actuator依赖,
在Controller上添加注解@RefreshScope
发送post请求请求localhost:8081/refresh
再重新访问即可(此方法了解即可)
实现配置文件的动态刷新:(config+bus)
spring-cloud-bus:消息总线,利用消息队列的方式实现动态的刷新,配置文件客户端(需要获取配置文件的微服务端)订阅此消息队列(配置更新事件),当其中一个微服务节点的/bus/refresh端点被请求时,该实例就会向消息总线发送一个配置更新事件,其他实例获得该事件后也会更新配置。
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
在Controller上添加注解@RefreshScope
安装rabbitmq
client模块中配置文件(bootstrap.yml)中添加
spring:
rabbitmq:
host: #rabbitmq所在主机ip地址
port: #rabbitmq端口
username: guest
password: guest
management:
endpoints:
web:
exposure:
include:bus-refresh
启动配置中心服务端与客户端(可以启动多个不同端口的客户端便于测试)
更改git服务器上的配置文件,此时直接通过服务端访问可以得到修改后的内容,但客户端不会跟着刷新。
发送post请求(可以使用postman或者终端)
访问http://localhost:9201(其中一个客户端的ip)/actuator/bus-refresh
再次通过客户端访问(http://localhost:9201/value)可以得到修改后的配置文件内容
此时其他客户端,例如(http://localhost:9202/value)也会一起进行更新