消息总线 Spring Cloud Bus

本文介绍了如何使用Spring Cloud Bus结合RabbitMQ实现在分布式系统中广播配置变更。通过添加spring-cloud-starter-bus-amqp依赖,配置RabbitMQ,并在Application中启用Bus,可以实现配置文件的动态刷新。
摘要由CSDN通过智能技术生成

SpringCloud视频教程:

https://ke.qq.com/course/2805647?tuin=a3e3fb1&from_uin=171851697&from=1000201007

个人博客纯净版

http://www.51ufo.cn/%E5%BE%AE%E6%9C%8D%E5%8A%A1/%E5%88%86%E5%B8%83%E5%BC%8F/2020/07/11/SpringCloud%E5%85%A5%E9%97%A814-%E6%B6%88%E6%81%AF%E6%80%BB%E7%BA%BF-Spring-Cloud-Bus.html

Spring Cloud Bus 将分布式的节点用轻量的消息代理连接起来。它可以用于广播配置文件的更改或者服务之间的通讯,也可以用于监控。这节课讲述的是用Spring Cloud Bus实现通知微服务架构的配置文件的更改。 准备工作

本文还是基于上一篇文章来实现。按照官方文档,我们只需要在配置文件中配置 spring-cloud-starter-bus-amqp ;这就是说我们需要装rabbitmq。至于怎么使用 rabbitmq,请自行百度

改造config-client

在pom文件加上起步依赖spring-cloud-starter-bus-amqp,完整的配置文件如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- spring cloud config 客户端包 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
        <version>2.0.4.RELEASE</version>
    </dependency>
    <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>
</dependencies>

在配置文件bootstrap.yml中加上rabbitmq的配置,包括rabbitmq的地址、端口,用户名、密码。并需要加上spring.cloud.bus的三个配置,具体如下:

server:
  port: 8881
spring:
  application:
    name: config-client
  cloud:
    config:
      uri: http://localhost:8888/
      label: master
      profile: dev
    bus:
      enabled: true
      trace:
        enabled: true
  rabbitmq:
    host: 192.168.192.10
    port: 5672
    username: guest
    password: guest
management:
  endpoints:
    web:
      exposure:
        include: bus-refresh

在Application启动类添加@RefreshScope注解 ,代码如下

@RefreshScope
@RestController
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Value("${user.name}")
    String name;
    @RequestMapping(value = "/hello")
    public String hi(){
        return "hello," + name;
    }
}

分别启动config-server和config-client服务,在浏览器中访问http://localhost:8881/hello 返回信息如下:

hello,zhangsan

将git配置中的user.name属性改为如下:

 

通过postman发送post请求调用localhost:8881/actuator/bus-refresh,如下:

postman.png

配置刷新后在浏览器再次访问http://localhost:8881/hello,返回信息如下:

hello,lisi

此时说明刷新配置生效了。

本文代码git地址 https://gitee.com/xmingtx/springcloud-lesson.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值