天天看点

第八节:消息总线

一、安装RabbitMQ

         参考链接:windows下 安装 rabbitMQ 及操作常用命令

                           RabbitMQ入门(一)——RabbitMQ的安装以及使用(Windows环境下)

二、基本思路

         基本思路就是,某个Client发送一个  刷新Git配置文件的请求。然后通过消息总线向其它服务器传播此通知,通知所有的服务器更新配置文件,从而使整个微服务集群都达到更新配置文件的目的。

        基本流程是:

         (1)PC端向 8882 Client 发送一个/bus/refresh请求,所以8882Client就会重新从8888端口的配置中心Config-server上获取最新的配置文件信息。

         (2)重新获取到配置文件信息后,8882端口将Git上的有最新配置文件的消息发送给消息总线。

         (3)消息总线通过消息中间件,例如RabbitMQ向其它微服务Client发送消息,所以其它微服务8881Client在收到通知后重新向配置中心请求最新的配置文件信息。

三、改造配置中心config-client

        3.1  导入消息总线依赖

<dependency>
        <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-bus-amqp</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>      

        3.2  编写配置文件

        在bootstrap.properties中新增加RabbitMQ配置以及消息总线配置

#配置RabbitMQ
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

#消息总线配置
spring.cloud.bus.enabled=true
spring.cloud.bus.trace.enabled=true
management.endpoints.web.exposure.include=bus-refresh      

         3.3  编写启动类

package com.safesoft.client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

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

         3.4  为要被刷新从配置文件中的类增加@RefreshScope注解

@RestController
@RefreshScope
public class IndexController {
    @Value("${jay.label}")
    private String label;

    @RequestMapping("/hello")
    public String test() {
        return label;
    }
}      

        3.5  测试

        (1)首先开启8761的注册中心,开启8001的配置中心,开启两个Client,分别部署在8004与8005端口。

第八节:消息总线

       (2)访问:​​http://localhost:8004/hello​​​,得到GIT的配置信息。访问​​http://localhost:8005/hello​​结果也一样。

第八节:消息总线
第八节:消息总线

        (3)更新配置文件,并将其推送到GitHub上。再访问​​http://localhost:8004/hello​​看看效果。

        我录制了一张动图,详细展示了这个过程。

        起初的配置文件被我修改成了 test444444,目标将其改为test666666。

        修改GitHub上的数据并提交。然后通过POSTMAN发送​​http://localhost:8004/actuator/bus-refresh​​。也就是说,8004端口的数据先重新加载。然后通过RabbitMQ发送消息,通知部署在8005端口的微服务也要重新读取配置文件。

        测试的时候因为GitHub的网络延迟,还有消息总线通过RabbitMQ发送消息到别的服务器也要一点时间,所以部分操作有点慢,请各位看官耐心一下,大宇先说声抱歉了。

第八节:消息总线

四、源码下载

         ​​https://github.com/hairdryre/Study_SpringCloud​​

继续阅读