-
Notifications
You must be signed in to change notification settings - Fork 60
统一配置中心及使用Spring Cloud Bus自动刷新配置
Exrick edited this page Sep 13, 2018
·
2 revisions
spring:
application:
name: config-server
cloud:
config:
server:
# Git/SVN配置 更换svn此处改为svn:
git:
# 仓库地址与账密
uri: https://github.com/Exrick/xcloud-config
# private仓库需配置账密
username:
password:
# 指定文件夹 相对搜索路径 可以配置多个
search-paths:
# 指定从git上拉取至本地保存路径
# basedir:
# 快速返回失败信息
fail-fast: true
-
config-server会从远程仓库中拉取配置至本地
-
当远程仓库是私密时请配置账密
-
basedir说明
-
默认情况下,从远程仓库拉去的配置文件会放在系统临时目录中,前缀为config-repo-。例如,在Linux上,它可能是/tmp/config-repo-。某些操作系统会定期清理临时目录。这可能会导致意外找不到配置。要避免此问题,请通过设置更改Config Server使用的目录,spring.cloud.config.server.git.basedir或spring.cloud.config.server.svn.basedir更改拉取的配置文件存放的目录。
-
可在日志中看到具体目录
-
spring:
cloud:
config:
# 启用读取远程配置中心
enabled: true
discovery:
# 开启通过服务来访问config-server
enabled: true
# 指定服务发现组件中config的serviceId
service-id: config-server
# 对应配置文件名规则: /{label}/{search-paths}/{name或application.name}-{profile}}
name: base
profile: dev
# 对应分支 默认master
label: master
eureka:
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
client:
serviceUrl:
defaultZone: http://localhost:1000/eureka/
- 映射对应规则,也可在日志中找到
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
即可在浏览器中访问测试:
http://localhost:1001/base-dev.yml
http://localhost:1001/base-dev.json
http://localhost:1001/base-dev.properties
...
踩坑提醒
- 由于配置文件加载顺序
bootstrap > 配置中心 > application
,原eureka注册中心配置在application.yml中,现在需移至bootstrap.yml中 否则会报错No instances found of configserver
- 其本身也是微服务,修改端口,多启动几个
config-server
实例即可
- 这里消息队列使用到 RabbitMQ,你也可以使用 kafka ,详见官方文档
- 官网下载地址
- Docker安装 Docker镜像地址
docker run -d --hostname rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.7.7-management
这里就不提供其他操作系统安装方法,请自行百度,因为不会Docker的话,对不起,我们不能一起玩微服务。
- 导入依赖(config-server和使用到远程配置的服务都需添加,本项目中已放置父pom中)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
- config-server添加rabbitmq配置并暴露所有actuator节点
- 访问 http://127.0.0.1:1001/actuator 即可看到 http://127.0.0.1:1001/actuator/bus-refresh (注意为POST请求)
spring:
application:
name: config-server
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
management:
endpoints:
web:
exposure:
include: '*'
- 需要使用到动态刷新配置的类上记得加上注解
@RefreshScope
- 注意在用到远程配置的服务中也添加rabbitmq配置,本项目以
base-server
为例,到此配置中心通过Spring Cloud Bus已与各服务构成了消息队列间通信。当我们修改git仓库中配置提交后,访问节点 http://127.0.0.1:1001/actuator/bus-refresh (POST请求),配置即可动态刷新
- 利用git仓库的webhooks我们可以实现自动刷新配置,每次push后git会给我们填入的URL发送一个POST请求,注意此处Spring Cloud Bus为我们提供的节点为
/monitor
- 作者:Exrick
- 版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。