问题

在上一篇文章Spring Cloud Config Server简介http://sivalabs.in/2017/08/spring-cloud-tutorials-introduction-to-spring-cloud-config-server/ )中,我们已经了解了如何使用Spring Cloud配置服务器。

但是,问题是要重新加载Config Client应用程序中的配置更改,我们需要手动触发/ refresh端点。 如果您有大量的应用程序,这是不切实际和可行的。

Spring Cloud Bus模块可用于通过消息代理链接多个应用程序,并且我们可以广播配置更改。

让我们看看如何使用RabbitMQ作为消息代理,并连接多个应用程序以接收配置更改事件并刷新边界属性值。

在上一篇文章中,我们创建了Catalog-service作为SpringBoot应用程序,该应用程序充当Config Client。
让我们将Cloud Bus AMQP启动器添加到catalog-service / pom.xml

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

我们将使用RabbitMQ作为消息代理来广播配置更改。 我们可以在本地计算机上安装RabbitMQ或在Docker容器中运行。 我将使用以下docker-compose.yml配置在docker容器中运行Rabbitmq。

version: '2'
 
services:
  rabbitmq:
      container_name: rabbitmq-server
      image: 'rabbitmq:management'
      environment:
        - RABBITMQ_DEFAULT_USER=guest
        - RABBITMQ_DEFAULT_PASS=guest
      ports:
        - "5672:5672"
        - "15672:15672"

现在运行docker -compose启动rabbitmq容器。

接下来,我们需要在目录服务属性文件中配置RabbitMQ服务器的详细信息。

config-repo / catalogservice.properties

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

现在,我们可以运行catalog-service并重新加载配置更改,我们可以触发POST – http:// localhost:8181 / bus / refresh而不是http:// localhost:8181 / refresh

接下来,让我们创建另一个在端口8282上运行的SpringBoot应用程序订购服务 ,并配置Cloud Config Client,与目录服务相同的Cloud Bus AMQP。 订单服务也与目录服务连接到同一RabbitMQ消息代理。

现在运行应该在http:// localhost:8282上运行的订购服务应用程序。

现在,如果您同时更新商品目录服务和订购服务的属性并提交更改,则只需在任何一个应用程序上触发/ bus / refresh。 这将自动向所有订阅RabbitMQ的服务广播配置更改并刷新属性。

不仅是不同的应用程序,您可能还在不同的端口上运行同一应用程序的多个实例。 在这些情况下,相同的过程也适用。

因此,使用Spring Cloud Bus AMQP,只需一个/ bus / refresh请求就可以轻松重新加载任意数量的应用程序的配置更改。

本文的源代码位于https://github.com/sivaprasadreddy/spring-cloud-tutorial。

翻译自: https://www.javacodegeeks.com/2017/08/spring-cloud-tutorials-auto-refresh-config-changes-using-spring-cloud-bus.html