5Cloud Config改造(RabbitMQ) · SpringCloud微服务实战 · 看云

导航

本节代码地址


在config配置那一节我们提过,如果一个ConfigServer 有多个客户端,ConfigServer 修改了数据,一个个刷新客户端的/actuator/refresh 对开发很不友好,下面我们通过引入Spring Cloud Bus 总线来解决问题,ConfigServer 变更后推送给总线,由总线来向各个客户端刷新配置。过程如下图:
3e6d7b5c92ed06065c593b5c976f8d34_MD5.webp

下面我们新建一个项目来演示

1.新建项目fw-cloud-config-amqp-client

acf53adfdfaf270e54ed2b6ecd96d06c_MD5.webp

1.1 maven 配置

fw-cloud-config-native-client多加了一个spring-cloud-starter-bus-amqp

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-bus-amqp</artifactId>
    </dependency>
</dependencies>

1.2 新建FwConfigAmqpClientApplication启动类

@EnableDiscoveryClient
@SpringBootApplication
public class FwConfigAmqpClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(FwConfigAmqpClientApplication.class, args);
    }
}

1.3 配置文件bootstrap.yml

这里我们选用基于git 且使用服务发现的方式(先把Config Server启动起来)
fw-cloud-config-native-client我们吧添加了rabbitmq相关的配置信息
并且把bus-refresh接口暴漏出来

server:
  port: 8779
spring:
  application:
    name: fw-register-eureka-client
  cloud:
    config: 
      profile: dev
      label: master
      discovery: #基于服务发现的
        enabled: true
        service-id: fw-config-server 
  rabbitmq:
    host: localhost
    port: 5672
    username: fwcloud
    password: fwcloud
management:
  endpoints:
    web:
      exposure:
        include: refresh,health,info,bus-refresh

注意:Spring boot 2.0的改动较大,/ bus / refresh全部整合到执行器里面了,变成了/ actuator / bus-refresh,所以之前1.x的management.security.enabled全部失效,不适用于2.0 ,2.0的性能配置是这样的:

management:
  endpoints:
    web:
      exposure:
        include:*

1.4 启动项目并postman 测试

localhost:8779/api/version get请求
返回结果
eureka-2.0
修改version的值为3.0,提交git并postman测试
localhost:8779/actuator/bus-refresh post请求
返回结果
eureka-3.0

1.5设置自动触发

配置一个可以直接访问的地址,不要是localhost,可以再每次变更之后动态刷新配置
2f46679110f930102e156c3cea4404c9_MD5.png

2.小结

我们已经通过Spring Cloud Bus 与 Spring Cloud Config的整合,并已RabbitMQ作为消息代理,实现了配置的动态更新