spring监听nacos配置中心文件变化的两种方式

1.前置条件

1.1依赖

    <properties>
        <spring-boot.version>2.4.2</spring-boot.version>
        <spring-cloud.version>2020.0.1</spring-cloud.version>
        <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>

spring-cloud-starter-bootstrap需要引入

1.2配置

1.2.1 nocos配置

我们要监听other.yaml文件的other.name|age属性
在这里插入图片描述

1.2.2 bootstrap.yml文件内容

server:
  port: 8080
---
spring:
  application:
  #需要指定
    name: gateway
  profiles:
    active: dev
---
spring:
  cloud:
    nacos:
      discovery:
      #需要配置
        server-addr: 192.168.56.150:8848
        group: DEFAULT_GROUP
      config:
            #需要配置
        server-addr: 192.168.56.150:8848
        group: DEFAULT_GROUP
        file-extension: yaml
        extension-configs:
          - data-id: gateway-routes.yaml
            group: DEFAULT_GROUP
            refresh: true
          - data-id: other.yaml
            group: DEFAULT_GROUP
            refresh: true

1.3属性文件映射

@RefreshScope//Bean 在运行时刷新
@ConfigurationProperties(prefix = "other")//要绑定外部属性的前缀
@Configuration//设置为bean
public class Config {
	//映射other.yaml ->oher.name
    private String name;
    
    //映射other.yaml ->oher.age
    private String age;
    
    //启动后定时打印当前bean中的值,不推荐这种方式,做测试方法
    @PostConstruct
    public void testValueIsChange() {
        new Thread(() -> {
            int i = 1;
            do {
                Config bean = SpringBeanUtil.getBean(Config.class);
                System.out.println("--- >" + i + "-->当前bean值: " + "name:" + bean.getName() + "|age:" + bean.getAge());
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                i++;
            } while (true);
        }).start();
    }
    
   //....get/set方法
}  

2监听

2.1第一种方式nacos的SDK

@Component
public class OtherListen {

    @Resource//注入NacosConfigManager
    public void nacosListen(NacosConfigManager nacosConfigManager) {
    	//获取配置中心服务
        ConfigService configService = nacosConfigManager.getConfigService();
        try {
        	//对配置中心添加监听(配置文件的dataId,group)
            configService.addListener("other.yaml", "DEFAULT_GROUP", new AbstractConfigChangeListener() {
            	//监听后的处理逻辑
                @Override
                public void receiveConfigChange(ConfigChangeEvent configChangeEvent) {
                    for (ConfigChangeItem changeItem : configChangeEvent.getChangeItems()) {
                        System.out.println("nacos方式监听" + changeItem.getKey() + "-----" + changeItem.getNewValue());
                    }
                }
            });
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }
    
	//注解监听spring.cloud环境下需要添加额外依赖,可以参考官方文档,这里不做演示
    @NacosConfigListener(dataId = "other.yaml")
    public void onReceived(String value) {
        System.out.println("onReceived : " + value);
    }
}

2.2第二种方式监听spring的环境修改

//利用spring事件通知机制

@Component
public class OtherListen implements ApplicationListener<EnvironmentChangeEvent> {
    @Resource
    private ConfigurableEnvironment environment;
    @Override
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        for (String key : event.getKeys()) {
            System.out.println("spring方式监听: key:" + key + "value:" + environment.getProperty(key));
        }
    }
}

3.测试

  1. 启动后,正常读取到nacos other.yaml数据
    在这里插入图片描述

  2. 修改nacos other.yaml数据
    在这里插入图片描述

  3. 查看监听是否正常
    spring监听正常
    在这里插入图片描述
    nacosSDk监听正常

在这里插入图片描述

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 中,可以通过 `@Value` 注解来获取 Nacos 配置中心的配置,同时也可以通过 `@NacosPropertySource` 注解来指定 Nacos 配置中心的配置源。但是,如果需要实时监听 Nacos 配置文件变化,可以使用 Nacos 提供的监听器来实现。 具体步骤如下: 1. 在 `pom.xml` 文件中添加 Nacos 配置中心的依赖: ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> ``` 2. 在 `application.properties` 或 `application.yml` 文件中添加 Nacos 配置中心的配置: ```yml spring.cloud.nacos.config.server-addr=127.0.0.1:8848 spring.cloud.nacos.config.namespace=your_namespace spring.cloud.nacos.config.group=your_group spring.cloud.nacos.config.file-extension=properties spring.cloud.nacos.config.shared-dataids=demo.properties ``` 3. 创建一个配置类,使用 `@NacosPropertySource` 注解指定 Nacos 配置中心的配置源: ```java @Configuration @NacosPropertySource(dataId = "demo.properties", autoRefreshed = true) public class NacosConfig { @Value("${demo.config}") private String config; @PostConstruct public void init() { System.out.println(config); } } ``` 4. 在启动类上添加 `@EnableDiscoveryClient` 注解,以启用 Nacos 服务注册与发现功能。 ```java @SpringBootApplication @EnableDiscoveryClient public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 通过上述步骤,就可以实现 Spring Boot 监听 Nacos 配置文件变化了。当 Nacos 配置中心配置文件发生变化时,应用程序会自动更新配置,并且调用 `@Value` 注解绑定的字段也会更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值