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监听正常

在这里插入图片描述

Nacos是一个配置中心,可以用于管理应用程序的配置信息。它提供了两种方式实现动态刷新配置,分别是Push模式和Pull模式。 Push模式是指配置中心配置信息主动推送给应用程序,应用程序只需要监听配置中心变化即可。例如,在Java应用程序中使用Nacos配置中心,可以使用Nacos提供的监听器实现动态刷新配置: ``` import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.Listener; public class NacosConfigListener { public static void main(String[] args) throws Exception { ConfigService configService = NacosFactory.createConfigService("localhost:8848"); String dataId = "example"; String group = "DEFAULT_GROUP"; configService.addListener(dataId, group, new Listener() { @Override public void receiveConfigInfo(String configInfo) { System.out.println("Received new config: " + configInfo); } @Override public Executor getExecutor() { return null; } }); } } ``` 上述代码中,`addListener`方法会监听配置中心中`dataId`为`example`、`group`为`DEFAULT_GROUP`的配置信息变化,并在收到新的配置信息时输出到控制台。 Pull模式是指应用程序主动从配置中心获取配置信息。例如,在Spring应用程序中使用Nacos配置中心,可以使用Nacos提供的`@NacosValue`注解实现动态刷新配置: ``` import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class ExampleComponent { @Value("${example.property}") private String exampleProperty; public void doSomething() { System.out.println("Current example property value: " + exampleProperty); } } ``` 上述代码中,`@Value`注解会从配置中心获取`example.property`配置信息,并将其注入到`exampleProperty`字段中,应用程序可以在运行时动态刷新配置信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值