Spring Cloud 学习教程——第七篇:配置中心消息总线(Spring Cloud Bus)

Spring Cloud Bus ?

Spring cloud bus通过轻量消息代理连接各个分布的节点。这会用在广播状态的变化(例如配置变化)或者其他的消息指令。Spring bus的一个核心思想是通过分布式的启动器对spring boot应用进行扩展,也可以用来建立一个多个应用之间的通信频道。目前唯一实现的方式是用AMQP消息代理作为通道,同样特性的设置(有些取决于通道的设置)在更多通道的文档中。

Spring cloud bus被国内很多都翻译为消息总线,也挺形象的。大家可以将它理解为管理和传播所有分布式项目中的消息既可,其实本质是利用了MQ的广播机制在分布式的系统中传播消息,目前常用的有Kafka和RabbitMQ。利用bus的机制可以做很多的事情,其中配置中心客户端刷新就是典型的应用场景之一,我们用一张图来描述bus在配置中心使用的机制。

Spring Cloud 学习教程——第七篇:配置中心消息总线(Spring Cloud Bus)_第1张图片

Spring Cloud Bus做配置更新步骤如下:

1、提交代码触发post请求给/actuator/bus-refresh/
2、server端接收到请求并发送给Spring Cloud Bus
3、Spring Cloud bus接到消息并通知给其它客户端
4、其它客户端接收到通知,请求Server端获取最新配置
5、全部客户端均获取到最新的配置

我们需要在 config-server 端的代码做一些改动,来支持 bus/refresh 达到自动刷新的需求。

  • 添加依赖

        
            org.springframework.cloud
            spring-cloud-starter-bus-amqp
        

        
            org.springframework.boot
            spring-boot-starter-actuator
        

        
            org.springframework.boot
            spring-boot-starter-security
        
  • 配置文件
server:
  port: 8001
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: ****     # 配置git仓库的地址
          search-paths: config-files  # git仓库地址下的相对地址,可以配置多个,用,分割。
          username: username                                        # git仓库的账号
          password: password                                    # git仓库的密码
# rabbitmq 相关配置
  rabbitmq:
    host: 192.168.0.6
    port: 5672
    username: guest  # 默认账号
    password: guest  #默认密码

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8000/eureka/   # 注册中心eurka地址

# 配置关闭安全验证
management:
  security:
     enabled: false
  • 启动 config-server

启动 cloud-config,访问 http://127.0.0.1:15672,登录后,可以看到队列中已经多出一个队列。

  • 改造 config-client,添加依赖

    org.springframework.boot
    spring-boot-starter-actuator


    org.springframework.cloud
    spring-cloud-starter-bus-amqp

  • 配置配置文件
spring:
  rabbitmq:
    port: 5672
    host: 127.0.0.1
    username: guest
    password: guest
management:
  security:
    enabled: false
  • 加入注解
    需要在使用到远程配置文件的 类上添加 @RefreshScope

  • 启动 config-client

启动 config-client,访问 http://192.168.174.128:15672,可以看到又多出一个 队列。

  • 动态刷新验证
    1、修改远程配置文件内容。
    2、访问 config-client ,发现 配置没有更改。
    3、手动发送 post ,http://127.0.0.1:8001/actuator/bus-refresh ,发现server 端 ,client 端都更新了远程配置文件信息 。

你可能感兴趣的:(Spring Cloud 学习教程——第七篇:配置中心消息总线(Spring Cloud Bus))