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

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

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

相关推荐

无力吐槽的自动续费(你被自动续费困扰过吗?)

今天因为工作需要,需要在百度文库上下载一篇文章。没办法,确实需要也有必要,只能老老实实的按要求买了个VIP。过去在百度文库上有过类似经历,当时为了写论文买了一个月的VIP,后面也没有太注意,直到第二个...

百度文库推出“文源计划”创作者可一键认领文档

11月7日,百度文库发布了旨在保护创作者权益的“文源计划”。所谓“文源计划”,即为每一篇文档找到源头,让创作者享受更多的权益。据百度文库总经理李小婉介绍,文源计划分为三部分,分别是版权认证、版权扶持和...

有开放大学学号的同学,百度文库高校版可以用了。

还在网上找百度文库的下载方式,只要从身边的朋友在读开放大学的,那他(她)的学号就可以登陆到国家开放大学图书馆,还使用百度文库高校版来下载。与百度文库稍有不同,但足够使用了。现转国图链接如下:htt...

搜索资源方法推荐(搜索资源的方法)

今天msgbox就要教大家如何又快又准的搜到各类资源,第一点,排除干扰百度搜索出来啊经常前排展示它的产品以及百度文库,如何去除呢?很简单,后面输入空格减号百度文库,比如你搜高等数学百度文库很多,只要后...

一行代码搞定百度文库VIP功能(2021百度文库vip账号密码共享)

百度文库作为大家常用查资料找文档的平台,大多数文档我们都可以直接在百度文库找到,然而百度文库也有让人头痛的时候。好不容易找到一篇合适的文档,当你准备复制的时候他却提示你需要开通VIP才能复制~~~下载...

百度文库文档批量上传工具用户说明书

百度文库文档批量上传工具用户说明书1、软件主要功能1、批量上传文档到百度文库,支持上传到收费、VIP专享、优享以及共享。2、支持自动分类和自动获取标签3、支持多用户切换,一个账户传满可以切换到...

百度文库现在都看不到文档是否上传成功,要凉了吗?

打开知识店铺,百度文库文档里显示都是下载这一按键,上传的文档也看不到是否成功?咋情况,要取消了吗?没通过审核的也不让你删除,是几个意思,想通吃吗?现在百度上传文档也很费劲,有时弄了半天的资料上传审核过...

微信推广引流108式:利用百度文库长期分享软文引流

百度文库相对于百度知道、百度百科来说,操作上没那么多条条框框,规则上也相对好把握些。做一条百度知道所花费的精力一般都会比做一条百度文库的要多些,老马个人操作下来觉得百度文库更好把握。但见仁见智吧,今天...

职场“避雷”指南 百度文库推出标准化劳动合同范本

轰轰烈烈的毕业季结束了,众多应届生在经过了“职场海选”后,已正式成为职场生力军的一员。这一阶段,除了熟悉业务,签订劳动合同、了解职场福利也迅速被提上日程。而随着国人法律意识的增强,百度文库内《劳动合同...

《百度文库》:素材精选宝库(百度文库官网首页)

《百度文库》:独特功能助力选择高质量素材在当今信息爆炸的时代,如何高效地获取并利用有价值的素材成为了许多人面临的挑战。而《百度文库》作为百度公司推出的一款在线文档分享平台,凭借其丰富的资源、强大的功能...

深度整合和开放AI能力 百度文库和网盘推出内容操作系统「沧舟OS」

【TechWeb】4月25日消息,Create2025百度AI开发者大会上,百度文库和百度网盘推出全球首个内容操作系统——沧舟OS。基于沧舟OS,百度文库APP全新上线「GenFlow超能搭子」...

女子发现大二作业被百度文库要求付费下载,律师:平台侵权,应赔偿

近日,28岁的黎女士在百度百科搜索家乡的小地名时,发现了自己在大二完成的课题作业。她继续搜索,发现多个平台收录了该文,比如豆丁网和文档之家等,有的还设置了付费或积分下载。2月15日,九派新闻记者以用户...

2016杀入百度文库的新捷径,只有少数人才知道的喔

百度的产品在SEO优化中的分量真不用多说,其实很多人都像我一样一直在找捷径。但是我经常发现很多人都是在用死方法。比如发贴吧发帖而不知道去申请一个吧主,知道自问自答而不知道去申请一个合作资格。口碑和贴吧...

百度文库付费文档搜索方法(百度文库付费文档搜索方法有哪些)

一直以来,百度文库中无论是个人中心还是个人主页,都没有像淘宝一样的店内搜索功能,连最近新开的知识店铺也没有设计店内搜索功能,这无论是对上传用户还是下载用户都不方便,上传用户想要搜索自己的文档无法办到...

供读者免费使用!泰达图书馆机构版百度文库新年上新啦

在泰达图书馆读者使用百度文库数字资源不需要VIP,免-费-用!惊不惊喜?快来了解一下吧……新年伊始,为满足区域企业、高校、科研院所以及居民群众在教学、科研及学习过程中,对各类文献资源的需求,泰达图书馆...

取消回复欢迎 发表评论: