微服务配置中心spring cloud使用nacos配置中心,nacos属性值自动刷新

本文介绍了如何在Spring Boot应用中使用Nacos配置中心,通过两种方式实现配置的动态刷新,包括直接读取环境变量和通过注解获取最新值,以简化参数管理并实现实时更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从nacos配置中心加载应用配置信息,用于启动参数,此时需要将nacos地址等配置信息添加到bootstap.yml文件中,而不是在application.yml中。

方式一:

yaml中开启 refresh-enabled=true 时(默认开启),通过applicationContext.getEnvironment.getProperty 直接获取

当程序启动后,会对指定的nacos配置进行监听,当nacos中的配置更新时,会自动同步到程序中,程序通过读取配置信息,获取变化后的配置信息。这种方式使用比较少。

1. 添加依赖

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

 2. 添加配置

spring:
  application:
    name: config-nacos  # 默认配置,与服务名相同的配置
  cloud:
    nacos:
      server-addr: 127.0.0.1:8848
      config:
        username: nacos
        password: nacos
        namespace: 6081bcbc-43aa-4b29-ac07-57fdb6dbf953
        # namespace: box
        file-extension: yaml               # 配置格式
        refresh-enabled: true              # 动态感知

  3. 通过系统属性获取变化后的配置信息

@SpringBootApplication
public class NacosConfigSimpleApplication {
    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext applicationContext =
          		SpringApplication.run(NacosConfigSimpleApplication.class, args);
        //取到Spring的配置环境
        while(true){
            ConfigurableEnvironment environment = applicationContext.getEnvironment();
            String username = environment.getProperty("user.name");
            String age = environment.getProperty("user.age");
            System.out.println("username:"+username+" | age:"+age);
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

方式二:

springboot依赖,@NacosValue获取最新值nacos配置信息需要写在配置类上

1. 添加依赖

<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>${latest.version}</version>
</dependency>

2. 添加配置类:

@Configuration
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosPropertySource(dataId = "example", group="test",autoRefreshed = true)
public class NacosConfiguration { }

3. 添加测试类

@Controller
public class ConfigController {
    @NacosValue(value = "${test.data}", autoRefreshed = true)
    private boolean data;                                     
 
    @RequestMapping(value = "/test", method = GET)
    @ResponseBody
    public boolean get() { return data; }
}

方式三:

结合springcloud ,@Value获取最新值一定要加@RefreshScope注解,配置文件中配置refresh: true

1. 添加依赖

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

2. 配置参数

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

3. 测试类:

@Value获取最新值 + @RefreshScope

@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;
    }
}

通过nacos,可以做到在nacos配置中心动态配置参数之后立即生效。这样就避免了定时轮询参数是否有变化的必要了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿20

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值