SpringCloud Config(配置中心) 配置服务自动刷新

Myth丶恋晨 2022-10-28 15:27 332阅读 0赞

概述

配置中心负责统一保存微服务的配置文件(yml或properties文件),配置文件一般是从git库(或其它后端)中拉取。

微服务启动时,会从配置中心拉取配置文件。如果配置中心有对应的配置文件,则会覆盖服务本地的配置文件中对应的属性。

当git库有新的提交时,通过webhook通知配置中心。webhook会带上修改的内容,配置中心找到此次修改的配置文件,通过Spring Cloud Bus通知对应的服务刷新配置。

架构

springboot:2.3.3
spring cloud: Hoxton.SR8
在这里插入图片描述

Config Server端配置

依赖

  1. <!-- config-server依赖 -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-config-server</artifactId>
  5. </dependency>
  6. <!-- springcloud-bus依赖实现配置自动更新,rabbitmq -->
  7. <dependency>
  8. <groupId>org.springframework.cloud</groupId>
  9. <artifactId>spring-cloud-starter-bus-amqp</artifactId>
  10. </dependency>
  11. <!-- webhook通知配置中心刷新的接口 -->
  12. <dependency>
  13. <groupId>org.springframework.cloud</groupId>
  14. <artifactId>spring-cloud-config-monitor</artifactId>
  15. </dependency>

配置文件

  1. spring:
  2. cloud:
  3. config:
  4. server:
  5. git:
  6. uri: git@192.168.1.33:root/leve-config-repository.git
  7. search-paths: config
  8. timeout: 10
  9. ignore-local-ssh-settings: true
  10. private-key: | -----BEGIN RSA PRIVATE KEY----- xx -----END RSA PRIVATE KEY-----
  11. rabbitmq:
  12. host: 192.168.1.57,192.168.1.58

启动类

启动类增加注解 @EnableConfigServer。

至此Config-Server端已配置完毕。

Config Client端配置

添加依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-bus-amqp</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.cloud</groupId>
  8. <artifactId>spring-cloud-starter-config</artifactId>
  9. </dependency>
  10. </dependencies>

配置文件

  1. spring:
  2. cloud:
  3. config:
  4. profile: dev #项目配置文件选择
  5. label: dev #git仓库的分支
  6. discovery: #通过注册中心发现配置中心
  7. enabled: true
  8. bus:
  9. enabled: true
  10. id: ${ spring.application.name}:${ spring.profiles.active}:${ random.value}
  11. rabbitmq: #本地环境不需要配置mq
  12. host: 192.168.1.57,192.168.1.58

记住配置bus.id,否则webhoob发送的事件会匹配不上服务。

代码

可以使用@RefreshScope 或 @ConfigurationProperties注解,获取配置文件中的属性并支持动态刷新。如:

  1. @Component
  2. @ConfigurationProperties("test.auth.client")
  3. @Getter
  4. @Setter
  5. public class AuthClientProp {
  6. /** * 授权id */
  7. private String id;
  8. /** * 授权密钥 */
  9. private String secret;
  10. }

@RefreshScope 和 @ConfigurationProperties的区别

Client端已经配置完毕。

配置webhook

在这里插入图片描述
上面是gitlab配置webhook的例子。
当push到dev分支时,gitlab调用配置中心的monitor接口通知更新。

至此,所有配置完成。

补充说明

  1. 如果使用的是蛇型命名,需要为ConfigServicePropertySourceLocator设置自定义Mapper的RestTemplate.
  2. 集成了Spring Cloud Bus后,不能使用stream3.0的写法来接收其它的mq消息,只能使用经典写法,否则接收不到mq消息。(springcloud 2020已解决这个问题)

发表评论

表情:
评论列表 (有 0 条评论,332人围观)

还没有评论,来说两句吧...

相关阅读