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

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

cac55 2025-03-24 14:17 11 浏览 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);
    }
}

相关推荐

用闲置电脑当软路由安装OpenWRT(小白教程)

话说软路由系统OpenWRT用起来真是香,里面的好多功能都是普通路由无法实现的,由于众所周知的原因,在这里就不细说,等安装完自己体验吧。今天就介绍用一台闲置的电脑(自带两个网口)充当软路由,安装Ope...

一招把废旧路由器改成交换机(用旧路由器做交换机)

家里面的路由器用个几年,就会WIFI变卡,新路由器买回来,旧路由器就没什么用了?我在这里教大家把老路由器变成交换机。近两年新出的路由器,基本都是2个LAN口,接网络设备还需要买交换机,淘汰下来的路由器...

如何将PC电脑变成web服务器:将内网主机映射到外网实现远程访问

我是艾西,今天跟大家分享内容还是比较多人问的一个问题:如何将PC电脑变成web服务器。内网主机作为web服务器,内容包括本地内网映射、多层内网映射解决方案、绕过电信80端口封锁、DDNS功能的实现(非...

电脑怎么改Wi-Fi密码(电脑怎么改wifi密码视频教程)

一.电脑打开“任意浏览器ie/google浏览器等”——>地址栏里输入管理ip地址然后按“回车键”打开该地址,如下图所示。二.输入正确的管理员密码——>点击“登录”即可(下图是PC版本的路...

旧路由器不要扔,可当电脑无线网卡使用,你还不知道吧!

家里有旧路由器,卖二手又不值钱,扔了又可惜。想不到路由器还有以下这些功能:扩大Wifi覆盖范围;充当电脑无线网卡;把这个技巧学起来,提升网络冲浪的幸福感!导航栏路由器恢复出厂设置(通用教程)有线桥接无...

硬件大师AIDA64 5.60.3716更新下载:“认准”Win10

著名硬件测试工具AIDA64更新至5.60.3716Beta版,本次更新修复了Win10Build版本号检测错误问题,识别更准确。另外还添加了对ITEIT8738F传感器、ASRock主板、NVI...

互联网病毒木马与盗版软件流量产业链(一)

A.相关地下产业链整体深度分析可能很多用户都有这样的经历,就是不管打开什么网站,甚至根本就没有打开浏览器,都会跳出来一堆的弹窗广告。那么,这个用户要么是中的病毒木马,或者是使用了盗版软件。不管是...

穿越火线tenparty.dat文件损坏怎么办?

很多玩家在玩火线的时候经常会因弹出错误代码,而被退出游戏。下面就教大家一些常见错误代码的解决方案。方法/步骤1SX提示码提示说明:您的电脑出现1,xxx,0(xxx代表任意数字)提示码,存在游...

办公小技巧015:如何关闭Windows Defender安全中心

WindowsDefenderWindowsDefender是Widows中自带杀毒软件,可以检测及清除潜藏在操作系统里的间谍软件及广告软件。为电脑提供最高强度的安全防护,也被誉为Windows的...

Win7/8.1/10团灭:微软发现严重漏洞

据外媒报道称,微软已经停止为Windows7发布新的安全更新了,理由是IE存在严重漏洞。存在严重漏洞的IE按照微软的说法,这个远程代码执行漏洞存在于IE浏览器处理脚本引擎对象的内存中。该漏洞可能以一...

WinCC flexible 2008 SP4 的安装步骤及系统要求

1、软件安装过程安装注意事项(必须严格遵守):软件仅支持以下操作系统(必须是微软原版的操作系统,Ghost版系统不支持,如番茄花园、雨林木风、电脑城装机版等):WinCCflexible2008...

Windows三方杀毒防护软件可能问题以及使用建议

在处理ECSWindows相关案例中,我们遇到很多奇怪的操作系统问题,例如软件安装失败,无法激活操作系统,无法访问本地磁盘,网络访问受到影响,系统蓝屏,系统Hang等,排查发现这与客户安装的各类杀...

杀毒软件被指泄露个人隐私(杀毒软件查出来一定是毒吗)

最近的多篇报道显示,你使用的杀毒软件在监视着你,而不仅仅是你计算机上的文件。2014年的一项研究使用虚拟机监视了杀毒软件产品向企业发送了什么信息。他们发现,所有测试的杀毒软件都给电脑分配了一个唯一的识...

开源杀毒软件ClamAV在推出约20年后终于到达1.0版本

ClamAV是一个开源的反病毒引擎,用于检测木马、病毒、恶意软件和其他恶意威胁。与商业Windows反恶意软件程序相比,它的检测水平相当低,但开发工作已经持续了几十年。该工具可用于所有平台,尽管它主要...

【Excel函数使用】时分秒时间怎么转换成秒?(二)

本节主要分享的函数是IFERROR和NUMBERVALUE上回我们用MID和FIND函数已经将数值提取出来,但是一些错误的返回值显示“#VALUE!”,此时我们需要检验错误返回值,并将错误值返回指定值...

取消回复欢迎 发表评论: