nacos属性值自动刷新

1.@NacosValue获取最新值

   引入jar包:  

          <dependency>

                 <groupId>com.alibaba.boot</groupId>

                 <artifactId>nacos-config-spring-boot-starter</artifactId>

                  <version>0.2.7</version>

            </dependency>

    编写配置类:

       @Configuration

       @EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))

       @NacosPropertySource(dataId = "example", group="test",autoRefreshed = true)

        public class NacosConfiguration { }

编写测试类:

       @Controller

       public class ConfigController {

         @NacosValue(value = "${test.data}", autoRefreshed = true)

           private boolean data;                                     

          @RequestMapping(value = "/test", method = GET)

          @ResponseBody

          public boolean get() { return data; }

      }

2.@Value获取最新值

   引入jar包:  

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.2.1.RELEASE</version>
</dependency>

 引入配置:

spring:
  application:
    name: example
  cloud:
    nacos:
      config:
        extension-configs[0]:
          dataId: test.yml
          group: test
          refresh: true
        server-addr:  127.0.0.1:8848
        namespace: c845e96f-4423-4618-8c26-5e4d510f566a
        enabled: true
        refresh-enabled: true

 编写测试类:

@RestController
@RefreshScope
public class TestController {
    @NacosValue(value = "${test.data}", autoRefreshed = true)
    private String data;
    @Value(value = "${test.data}")
    private String datas;
    @GetMapping("test")
    public String test() {
        return "data :" + data + ",datas="+datas;
    }
}

备注:方式一@NacosValue获取最新值nacos配置信息需要写在配置类上

          方式二@NacosValue获取不到值(如果需要使用该注解需要引入方式一的jar,但是不重启服务获取不到最新值),@Value获取最新值一定要加@RefreshScope注解,配置文件中配置refresh: true

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页