微信搜索
江南一点雨

Spring Cloud Bus

本文是松哥所录 《Spring Cloud 实践》视频教程的笔记,视频目录如下,如果大家对视频内容感兴趣,可以在公众号【江南一点雨】后台回复 vhr 查看视频详细介绍。

14.Spring Cloud Bus

Spring Cloud Bus 通过轻量级的消息代理连接各个微服务,可以用来广播配置文件的更改,或者管理服务监控。

安装 RabbitMQ。

Docker 中 RabbitMQ 安装命令:

docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 5672:5672 rabbitmq:3-management

首先给 config-server 和 config-client 分别加上 Spring Cloud Bus 依赖。

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

然后,给两个分别配置,使之都连接到 RabbitMQ 上:

spring.rabbitmq.host=192.168.91.128
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

同时,由于 configserver 将提供刷新接口,所以给 configserver 加上 actuator 依赖:

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

然后记得在 config-server 中,添加开启 bus-refresh 端点:

management.endpoints.web.exposure.include=bus-refresh

由于给 config-server 中的所有接口都添加了保护,所以刷新接口将无法直接访问,此时,可以通过修改 Security 配置,对端点的权限做出修改:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .csrf().disable();
    }
}

在这段配置中,开启了 HttpBasic 登录,这样,在发送刷新请求时,就可以直接通过 HttpBasic 配置认证信息了。

最后分别启动 config-server 和 config-client,然后修改配置信息提交到 GitHub,刷新 config-client 接口,查看是否有变化。

然后,发送如下 POST 请求:http://localhost:8081/actuator/bus-refresh

这个 post 是针对 config-server 的,config-server 会把这个刷新的指令传到 rabbitmq ,然后 rabbitmq 再把指令传给 各个 client。

逐个刷新

如果更新配置文件之后,不希望每一个微服务都去刷新配置文件,那么可以通过如下配置解决问题。

首先,给每一个 config-client 添加一个 instance-id:

eureka.instance.instance-id={spring.application.name}:{server.port}

然后,对 config-client 进行打包。

打包完成后,通过如下命令启动两个 config-client 实例:

java -jar config-client-0.0.1-SNAPSHOT.jar --server.port=8082
java -jar config-client-0.0.1-SNAPSHOT.jar --server.port=8083

修改配置文件,并且提交到 GitHub 之后,可以通过如下方式只刷新某一个微服务,例如只刷新 8082 的服务。

http://localhost:8081/actuator/bus-refresh/client1:8082

client1:8082 表示服务的 instance-id。

赞(3)
未经允许不得转载:江南一点雨 » Spring Cloud Bus
分享到: 更多 (0)
扫码关注微信公众号【江南一点雨】,回复 1024,查看松哥原创 Java 实战教程(图文+视频)。

专注 Java 一百年

关注我们国际站