spring cloud学习(六) 配置中心-自动更新

上一篇学习了spring cloud config的基本使用,但发现有个问题,就是每次更改配置后,都须要重启服务才能更新配置,这样确定是不行的。在上网查资料了解后,spring cloud支持经过AMQP来实现配置的实时更新。html

1、安装rabbitmq

1.1
若是要使用spring cloud的amqp,须要安装rabbitmq。咱们能够经过官网 https://www.rabbitmq.com/download.html 下载。我用的是mac,下载解压后,执行$RABBITMQ_HOME/sbin/rabbitmq-server来启动rabbitmq。git

rabbitmq的默认用户和密码都是guest,而默认端口是5672web

其余rabbitmq相关的这里就很少说了。spring

2、改造config-server和client-a

2.1
在config-server和client-a两个模块下的pom文件添加mvc

<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>

这里说明下spring-boot-starter-actuator是spring-boot自带的监控模块,咱们要使用spring-cloud-starter-bus-amqp的话,也必须加上。app

2.2
修改client-a模块的配置文件,主要是加上rabbitmq的配置,修改后以下,而config-server的配置文件不用修改spring-boot

server:
  port: 8910

eureka:
  client:
    serviceUrl:
          defaultZone: http://localhost:8010/eureka/

spring:
  application:
      name: client-a
  cloud:
      config:
        discovery:
          enabled: true #开启经过服务来访问Config Server的功能
          service-id: config-server
        profile: dev
        label: master

  rabbitmq:
      host: localhost
      port: 5672
      username: guest
      password: guest

2.3
注意,要达到配置自动更新,这里须要修改client-a的TestController,添加@RefreshScope注解post

@RestController
@RefreshScope
public class TestController {
    ...
}

2.4
重启config-server和client-a学习

能够注意下启动日志,其中应该有一段是
o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/bus/refresh],methods=[POST]}"
这就是触发配置刷新的方式。日志

打开http://localhost:8910/getProperties 应该看到配置仍是旧的配置

修改git上的配置文件

以post形式访问配置中心的http://localhost:8030/bus/refresh 来触发配置更新,看本地的日志,config-server和client-a都会有刷新配置的日志打印

再打开http://localhost:8910/getProperties 应该能够看到配置已经更新了

2.5
如今虽然能够不用重启服务就更新配置了,但仍是须要咱们手动操做,这样仍是不可取的。
因此,这里就要用到git的webhooks来达到自动更新配置。

打开git上配置仓库的地址,添加webhooks

上面的Payload URL就填写咱们的配置中心触发刷新的地址,固然这里不能写localhost啦,要外网访问地址才行。

还有这里面有个Secret的秘钥验证,若是这里填写的话,在配置文件上要写上encrypt.key与之对应。

相关文章
相关标签/搜索