第十五章:SpringCloud Config 配置手动刷新(了解,自动刷新是关键)

  1. 云栖社区>
  2. 博客>
  3. 正文

第十五章:SpringCloud Config 配置手动刷新(了解,自动刷新是关键)

微笑着生活 2017-12-14 17:56:00 浏览730
展开阅读全文

项目一旦放到生产环境,就需要不停机更改配置。比如更改一些线程池连接数什么的。或者是配置文件,这里我演示手动刷新git仓库上的配置文件

1. 添加pom

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

为什么一定要加actuator依赖呢?

img_68d3493775c41988a8cef7cdcb4d421d.png
image.png

有了actuator这个依赖,就可以使用/refresh 这个节点来刷新带有@RefreshScope注解服务的bean

2. 修改启动类

添加注解@RefreshScope
注解@RefreshScope拓展:

Refresh Scope
A Spring @Bean that is marked as @RefreshScope will get special treatment when there is a configuration change. This addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance if a DataSource has open connections when the database URL is changed via the Environment, we probably want the holders of those connections to be able to complete what they are doing. Then the next time someone borrows a connection from the pool he gets one with the new URL.

3. 在贴一下server 和 client 的配置代码

算了 不贴了,和以前一样的。
server:
Spring Cloud Config Server
client:
SpringCloud Config Client

启动config server和 client 服务

  1. 先来访问/profile 看服务是否正常运行


    img_7d5c7f3842b6c2bc4fd04ca7493d0ec4.png
  2. 修改git上的application-dev.yml配置


    img_fd2272f5f19b747b935ec5055e9490cf.png
    image.png

    img_5f9675de16718b6ce660d44ede551aa7.png
    image.png
  3. 再次访问/profile
    img_70af02da8cdb68a59e78d8d4b7ca6d20.png
    image.png

    我们发现它并没有发生变化。这需要我们的一个触发操作
    发送一个post请求给 /refresh
    img_d099112ba19dcb7262f2d5152671746c.png
    image.png

    img_f21378e57a3b33d32df4f7f2183472fd.png
    image.png

    再来看看 client端 控制台打印:
    img_1d48d3216ae67a376244808e35ae8d1d.png
    image.png

    意思是得到刷新指令后,重新从server获取 配置仓库的内容。

注意!@RefreshScope和 @Configuration在同一类上使用有冲突

@RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behaviour: e.g. it does not mean that all the @Beans defined in that class are themselves @RefreshScope. Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in @RefreshScope (in which it will be rebuilt on a refresh and its dependencies re-injected, at which point they will be re-initialized from the refreshed @Configuration).这并不意味着在该类中定义的所有@Beans本身都是@RefreshScope。 具体来说,任何依赖这些bean的东西都不能依赖于它们在刷新时被更新,除非它本身在@RefreshScope中(在刷新时它将被重建,并且它的依赖关系被重新注入,在这一点上它们将被 从刷新的@Configuration重新初始化)。

网友评论

登录后评论
0/500
评论
微笑着生活
+ 关注