百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Nacos进阶一之Nacos动态配置不生效故障排查

cac55 2025-03-24 14:17 13 浏览 0 评论

问题描述

我们开发了一个新的项目,项目核心功能包括对外提供的API接口 和 内部的定时任务。提供的API服务部署在4台服务器上,内部的定时任务部署在另外的2台服务器上。项目中使用了一些会变化的配置信息,这些配置信息,使用Nacos的配置中心管理。

修改Nacos中的配置信息,API网关服务配置会动态变化,但定时任务的服务的动态配置没有生效。这个问题排查,让我有点怀疑人生。下面列出我的排查步骤。

Nacos配置信息

Nacos的配置信息在 bootstrap.yml 中配置。bootstrap.yml 用来程序引导时执行,应用于更加早期配置信息读取。可以理解成系统级别的一些参数配置,这些参数一般是不会变动的。一旦bootStrap.yml 被加载,则内容不会被覆盖。

配置如下:

spring:
  application:
    name: order-web

##下面是环境区分,主要不同环境不同文件获取
---
#测试环境
spring:
  profiles: beta
  #nacos
  cloud:
    nacos:
      discovery:
        server-addr: 172.0.0.1:8848
        namespace: 21406c22-abef-4472-953e-tyea2aeb167a
        username: nacos
        password: nacos
      config:
        server-addr: 172.0.0.1:8848
        username: nacos
        password: nacos
        namespace: 21406c22-abef-4472-953e-tyea2aeb167a
        group: DEFAULT_GROUP
        shared-configs:
          - data-id: common-kafka.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-xxl-job.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-redis-order.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-mysql-order.yaml
            group: DEFAULT_GROUP
            refresh: true
       
        extension-configs:
          - data-id: order-config.yaml
            group: DEFAULT_GROUP
            refresh: true
---
#本地环境
spring:
  profiles: local
  #nacos
  cloud:
    nacos:
      discovery:
        server-addr: 172.0.0.1:8848
        namespace: 21406c22-abef-4472-953e-tyea2aeb167b
        username: nacos
        password: nacos
      config:
        server-addr: 172.0.0.1:8848
        username: nacos
        password: nacos
        namespace: 21406c22-abef-4472-953e-tyea2aeb167b
        group: DEFAULT_GROUP
        shared-configs:
          - data-id: common-kafka.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-xxl-job.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-redis-order.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-mysql-order.yaml
            group: DEFAULT_GROUP
            refresh: true
       
        extension-configs:
          - data-id: order-config.yaml
            group: DEFAULT_GROUP
            refresh: true
---
#正式环境
spring:
  profiles: prod
  #nacos
  cloud:
    nacos:
      discovery:
        server-addr: 172.0.0.1:8848
        namespace: 21406c22-abef-4472-953e-tyea2aeb167c
        username: nacos
        password: nacos
      config:
        server-addr: 172.0.0.1:8848
        username: nacos
        password: nacos
        namespace: 21406c22-abef-4472-953e-tyea2aeb167c
        group: DEFAULT_GROUP
        shared-configs:
          - data-id: common-kafka.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-xxl-job.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-redis-order.yaml
            group: DEFAULT_GROUP
            refresh: true

          - data-id: common-mysql-order.yaml
            group: DEFAULT_GROUP
            refresh: true
       
        extension-configs:
          - data-id: order-config.yaml
            group: DEFAULT_GROUP
            refresh: true

排查步骤

1、spring.application.name 放在bootstrap配置文件中

定义的 spring.application.name 配置在bootstrap.yml文件中,满足条件。

2、refresh 配置成 true

NacosConfigProperties 的refreshEnabled 默认值为 true,无须配置。shared-configs 和 extension-configs 中 refresh 配置须为true。我们配置的也没有问题。

refresh-enabled: true

3、通过添加打印日志排查

配置Nacos的打印日志,搜索 “ Refresh Nacos config group ”为空

logging:
  level:
    com:
      alibaba:
        nacos: DEBUG

NacosContextRefresher类定义如下:

public class NacosContextRefresher implements ApplicationListener, ApplicationContextAware {
  public void onApplicationEvent(ApplicationReadyEvent event) {
        if (this.ready.compareAndSet(false, true)) {
            this.registerNacosListenersForApplications();
        }
    }
  
     private void registerNacosListenersForApplications() {
        if (this.isRefreshEnabled()) {
            Iterator var1 = NacosPropertySourceRepository.getAll().iterator();

            while(var1.hasNext()) {
                NacosPropertySource propertySource = (NacosPropertySource)var1.next();
                if (propertySource.isRefreshable()) {
                    String dataId = propertySource.getDataId();
                    this.registerNacosListener(propertySource.getGroup(), dataId);
                }
            }
        }
    }

    private void registerNacosListener(final String groupKey, final String dataKey) {
        String key = NacosPropertySourceRepository.getMapKey(dataKey, groupKey);
        Listener listener = (Listener)this.listenerMap.computeIfAbsent(key, (lst) -> {
            return new AbstractSharedListener() {
                public void innerReceive(String dataId, String group, String configInfo) {
                    NacosContextRefresher.refreshCountIncrement();
                    NacosContextRefresher.this.nacosRefreshHistory.addRefreshRecord(dataId, group, configInfo);
                    NacosContextRefresher.this.applicationContext.publishEvent(new RefreshEvent(this, (Object)null, "Refresh Nacos config"));
                    if (NacosContextRefresher.log.isDebugEnabled()) {
                        NacosContextRefresher.log.debug(String.format("Refresh Nacos config group=%s,dataId=%s,configInfo=%s", group, dataId, configInfo));
                    }
                }
            };
        });

        try {
            this.configService.addListener(dataKey, groupKey, listener);
        } catch (NacosException var6) {
            log.warn(String.format("register fail for nacos listener ,dataId=[%s],group=[%s]", dataKey, groupKey), var6);
        }
    }
}

是什么原因导致 ApplicationListener 事件注册失败呢?

4、梳理 spring boot的启动流程

spring boot的核心类SpringApplication

public class SpringApplication {
  public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection exceptionReporters = new ArrayList();
        this.configureHeadlessProperty();
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        listeners.starting();

        Collection exceptionReporters;
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            this.configureIgnoreBeanInfo(environment);
            Banner printedBanner = this.printBanner(environment);
            context = this.createApplicationContext();
            exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            this.refreshContext(context);
            this.afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }

            listeners.started(context);
            this.callRunners(context, applicationArguments);
        } catch (Throwable var10) {
            this.handleRunFailure(context, var10, exceptionReporters, listeners);
            throw new IllegalStateException(var10);
        }

        try {
            listeners.running(context);
            return context;
        } catch (Throwable var9) {
            this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
            throw new IllegalStateException(var9);
        }
    }
}

发现SpringApplication的run()中有一行callRunners(context, applicationArguments); 这个方法内部代码使用主线程执行实现ApplicationRunner和CommandLineRunner的类中的代码,如果这些类中有阻塞,spring就不会执行。

经过上面的分析,可以确定问题了,项目中有些类实现了ApplicationRunner,同时有while(true)的代码,从而导致主线程阻塞在这里。排查我们的代码,如我们预测一样。

@Slf4j
@Component
public class PullIncomeSubscriber implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        doBusiness();
    }

    private void doBusiness() {
        while (true) {
            try {
                this.execute();
            } catch (Exception ex) {
                log.error("PullIncomeSubscriber.execute", ex);
                AlterFunction.sendMsg(AlterCodeEnum.AD_TRACK, "收益拉取任务异常:" + ex.getMessage());
            }
        }
    }

    public void execute() throws Exception {
        PullIncomTask pull = pullIncomeTaskCache.pull();

        if (Objects.isNull(pull)) {
            Thread.sleep(30000);
            return;
        }

        log.info("PullIncomeSubscriber.execute#adPlatfrom={}", pull.getAdPlatform());
        // 业务逻辑
    }
}

修改为异步线程执行,问题彻底解决。

@Slf4j
@Component
public class PullIncomeSubscriber implements ApplicationRunner {
    private final ExecutorService pool = Executors.newSingleThreadExecutor(); 

		@Override
    public void run(ApplicationArguments args) throws Exception {
        pool.execute(this::doBusiness);
    }
}

相关推荐

unetbootin中文版:能够将Linux系统装进U盘的U盘启动盘制作工具

unetbootin中文版是一款能够将Linux操作系统装进U盘或移动硬盘的U盘启动盘制作工具,制作好的U盘启动盘能够用于电脑的维护和系统还原等操作,使用起来非常地不错。该软件不会基于操作系统使用特定...

实用之选,实用之改:DELL 戴尔 灵越14CR-4528B 小改作业

昨天发布了一篇三脚架,今天有时间也写写早就准备写的DELL戴尔灵越14CR-4528B作业吧。话说上个笔记本还是2006年底买的华硕A6JE,电脑挺不错的,在家上上网也够用了,就是转轴设计缺陷,容...

教你如何制作一个启动U盘,从此电脑不用找专人做系统

在电脑使用中,老是遇到卡顿,蓝屏,重启等很多故障,大多都是因为自己日常使用习惯而造成的,很多用户在下载软件的时候不知不觉中都被安装许多乱七八糟的软件,当电脑乱七八糟的东西过多的时候我们就重新来装一个系...

8、Deepin操作系统启动盘(系统盘)制作

1、在Deepin官网https://www.deepin.org/zh/download/下载原版Deepin操作系统2、同时在Deepin官网https://www.deepin.org/zh/d...

电脑死机怎么办,电脑如何使用U盘重装系统

电脑死机是我们最常遇到的系统故障,遇到死机时通常重启就可以解决,不过系统损坏引起的死机就只能重装系统,那么电脑死机如何重装系统呢?下面来看看电脑死机怎么办如何使用U盘重装系统_小白一键重装系统官网。 ...

bootmgr is compressed无法启动系统

bootmgriscompressedPressCtrlAltDeltorestart,电脑启动后无法正常开机出现了这样的字样,就是说明你的C盘驱动被压缩解决方法:1、使用系统光盘或者...

新手教程!如何分辨BIOS启动列表(菜单)中的各种启动项

在BIOS启动菜单中识别各类启动项,是新手安装系统或调整启动顺序的必备技能。下面用最直观的方式,为你梳理常见启动项及其含义,帮助你快速上手:一、传统存储设备启动项1.Floppy(软盘驱动器)对应...

带回家的MINI客厅电脑,自学成才,分享U盘装系统教程

刚好老家新装修了房子,客厅买了个大电视,本来是想在客厅弄台主机,接电视玩,大屏幕玩的才爽,但是台式机箱太占地方了。网上逛了一圈,发现有专门的客厅电脑,就搞了一个,外形不错,放客厅很有档次,主要是主机太...

电脑基础知识:BIOS简介及其与Windows操作系统的关系

什么是BIOS?BIOS,全称BasicInputOutputSystem,即“基本输入输出系统”,是一段固化在电脑主板芯片上的底层固件程序。它类似于一款极简化的操作系统,负责电脑开机时的硬件初...

win 7 系统注册表文件丢失或损坏,求不重做系统的解决办法!

粉丝问题解答:win7系统注册表文件丢失或损坏,求不重做系统的解决办法!解决方法:你只需要有启动盘即可,不需要其他的。之所以要求启动盘,是因为下面要对系统文件进行还原覆盖,所以不能用原系统启动。用...

UEFI怎么装Win7 小编呕血解难点!

自从广开言路之后,小编就被你们害苦了,这不,一条评论又让小编彻夜难眠。另外某些小伙伴坐不上沙发后提出要上墙的需求,其实呢只要大家提出的问题具有普遍性、有难度、而且适合小编做微信内容的话,都有机会将你们...

固态攻坚战——ASUS 华硕k45v换固态、拆机清灰教程

作者:蘑菇爱上我现在固态白菜价固态对于电脑体验的提升还是很大的对于固态存储芯片的问题没什么好说的有钱mlc,没钱tlc,不需要考虑什么寿命的问题,我用了一年多的m600,写入才3TB品牌很重要,主控...

MBR启动报错?Win10不重装一样能好!

Win10一遇到启动故障,很多小伙伴可能就会抓瞎,这可怎么弄,我不会修复啊!其实大可不必惊慌,就像这种最常见的Winload启动错误,多半都是MBR分区表丢失造成的(UEFI分区模式的几乎没有这种故障...

从零开始:硬盘手动装系统全攻略

手动安装操作系统是计算机技术必备的基本技能。对于初学者来说,可能会感到有些挑战。但通过掌握硬盘手动装系统方法,你可以亲身体验整个安装过程,进而更好地理解操作系统的工作原理。本文将详细介绍硬盘手动装系统...

电脑开机后显示File:BCD错误0xc000000f

WIN7\WIN8\WIN101、一个win864位PE。这个64位PE的相关文件,路径在boot\BOOT.WIM实机测试,开机后显示File:\EFI\Microsoft\Boot\BCD,...

取消回复欢迎 发表评论: