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

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

一、安装rabbitmq

1.1
如果要使用spring cloud的amqp,需要安装rabbitmq。我们可以通过官网 https://www.rabbitmq.com/download.html 下载。我用的是mac,下载解压后,执行$RABBITMQ_HOME/sbin/rabbitmq-server来启动rabbitmq。

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

其他rabbitmq相关的这里就不多说了。

二、改造config-server和client-a

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

<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的话,也必须加上。

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

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

@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与之对应。

posted @ 2017-05-10 14:52  fengzp  阅读(18180)  评论(2编辑  收藏  举报