Spring Cloud配置中心配置项手动刷新

一、Spring使用配置中心

       spring cloud项目使用配置中心的过程这里不表(目前项目使用consul+git实现)

二、引入依赖

       作为使用配置中心的客户端,需要引入配置中心client的包

      <!-- 配置中心client -->
      <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
      </dependency>

      手动刷新配置时需要使用,同时也是作为监控分析进程状态的包

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

三、刷新配置 refresh

       此时已添加以上的依赖包,但是直接修改配置中心git目录中的配置项时,会发现配置并没有刷新,还需要以下步骤。

       1.添加依赖

            spring-boot-starter-actuator

       2.开启更新机制

            需要给加载变量的类上加上注解@RefreshScope(举例如下)

            @RestController
            @RefreshScope // 仅仅刷新@Value标记的值,不需要此注解。但如果要根据配置的值进行重新构造对象,则要设置。
            class HelloController {

 

                        @Value("${neo.hello}")
                        private String hello;

 

                        @RequestMapping("/hello")
                        public String hello() {
                                    return this.hello;
                        }
            }

        3.post请求/refresh (举例:http://localhost:10001/test/admin/refresh

           此时即已使用设置到git中的新配置值刷新了当前运行进程中的配置。

猜你喜欢

转载自blog.csdn.net/qq_33315102/article/details/80582533