nacos读取配置中心文件

nacos不仅是注册中心也可以作为配置中心,nacos会在启动过程中获取prefix、file-extension、group或profiles.active获取配置文件。那么如果配置中心有多个文件该如何获取?

获取多个配置文件原理

通过serverAddr和namespace获取nacos底层接口ConfigService,使用ConfigService通过参数DataId和group设置请求超时时间,发起http请求获取指定的配置信息。

创建文件

在nacos管理页面新建配置,设置DataId和GROUP、配置内容,
在这里插入图片描述

创建监听类

监听配置变化和初始化加载配置

@Slf4j
@Component
public class NacosConfigLocalCatch implements InitializingBean {
    private String data = null;

    @Autowired
    private NacosConfigProperties nacosConfigProperties;


    private static ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(2,4,1,TimeUnit.SECONDS, new LinkedBlockingDeque<>(100),new ThreadPoolExecutor.CallerRunsPolicy());

    @Override
    public void afterPropertiesSet(){
            this.listener();
    }

    public void listener() {
        Listener listener = new Listener() {
            @Override
            public Executor getExecutor() {
                return threadPoolExecutor;
            }
            @Override
            public void receiveConfigInfo(String config) {
                log.info("收到数据{}",config);
                data=config;
            }
        };
        ConfigService configService = this.getConfigService();
        try {
            String config = configService.getConfig("test", nacosConfigProperties.getGroup(), nacosConfigProperties.getTimeout());
            log.info("初始化获取配置信息", config);
            data=config;// 初始化
            // 监听
            configService.addListener("test", nacosConfigProperties.getGroup(), listener);
        } catch (NacosException e) {
            throw new RuntimeException("nacos异常,dataId:test{}",e);
        }
    }

    private ConfigService getConfigService() {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosConfigProperties.getServerAddr());
        properties.put(PropertyKeyConst.NAMESPACE, nacosConfigProperties.getNamespace());
        ConfigService configService;
        try {
            configService = NacosFactory.createConfigService(properties);
        } catch (NacosException e) {
            throw new RuntimeException("Nacos config 配置 异常{}",e);
        }
        return configService;
    }

    public String getData(){
        return data;
    }
}

data即为获取的配置信息


版权声明:本文为u010833154原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/u010833154/article/details/128580608