springboot定时任务:同时使用定时任务和websocket报错

背景

项目使用了websocket,实现了消息的实时推送。后来项目需要一个定时任务,使用org.springframework.scheduling.annotation的@EnableScheduling注解来实现,启动项目之后报错

clojure 复制代码
Bean 'com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration' of type [com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
scala 复制代码
Destroy method 'close' on bean with name 'nacosServiceRegistry' threw an exception: java.lang.NullPointerException

打断点进入代码发现是这个定时任务的bean为null

学习

由于先写的websocket推送消息,运行正常。之前一个项目只有一个定时任务(没有websocket)也是运行正常。综合网友的分析winky_L,是因为同时使用定时任务和websocket冲突导致

其他的一些学习kzcming
菜菜菜鸡

解决

1在启动类Application中加入task的initialize。【注意:如果继续报错,报错信息如下。报错信息解读:发现两个定时任务的bean,不知道使用哪一个,springboot报错,这时候在 taskScheduler方法中加上@Primary注解,告诉springboot使用这个自定义的定时任务】

bash 复制代码
Method nacosWatch in com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration required a single bean, but 2 were found:
	- taskScheduler: defined by method 'taskScheduler' in class path resource []
	- defaultSockJsTaskScheduler: defined by method 'defaultSockJsTaskScheduler' in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketConfiguration.class]

具体代码【】

bash 复制代码
    @Primary
    @Bean
    public TaskScheduler taskScheduler(){
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        //只有池子里的任务有执行结束后,池子之外的任务才有机会被加入执行。
        // 更糟的情况是,当池子里的任务都在因为异常或业务要求(比如出错无限重试)而导致池子永远无法得到释放,将导致固定值之外的任务永远不会被执行!
        //taskScheduler.setPoolSize允许动态设置池子的大小,可动态设置-> todo 有隐患
        taskScheduler.setPoolSize(10);
        taskScheduler.initialize();
        return taskScheduler;
    }

求解

问题1

刚开始在config类中添加该TaskScheduler 仍然启动不了,然后我放在启动类Application中就能启动成果。不知道这其中的原由

问题2

代码中和的这个线程池初始定义了poolsize,但是这里有隐患。

只有池子里的任务有执行结束后,池子之外的任务才有机会被加入执行。

更糟的情况是,当池子里的任务都在因为异常或业务要求(比如出错无限重试)而导致池子永远无法得到释放,将导致固定值之外的任务永远不会被执行!taskScheduler.setPoolSize允许动态设置池子的大小,可动态设置。看了一篇文章,但是还没有头绪daydayup

bash 复制代码
taskScheduler.setPoolSize(10);
        taskScheduler.initialize();
相关推荐
星浩AI6 小时前
AI 并不懂文字,它只认向量:一文搞懂 Embedding
后端
程序员博博6 小时前
这才是vibe coding正确的打开方式 - 手把手教你开发一个MCP服务
javascript·人工智能·后端
90后的晨仔7 小时前
阿里云服务器如何给子账号设置指定具体的那一台服务器?
后端
期待のcode7 小时前
springboot热部署
java·spring boot·后端
expect7g7 小时前
Paimon源码解读 -- FULL_COMPACTION_DELTA_COMMITS
大数据·后端·flink
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ7 小时前
aspect实现请求校验,但是WebSocket 端点类不能被 AOP 代理解决方案
网络·websocket·网络协议
Somehow0077 小时前
Spring Boot 集成 ElasticSearch 的简单示例
spring boot·设计
踏浪无痕7 小时前
周末拆解:QLExpress 如何做到不编译就能执行?
后端·算法·架构
222you7 小时前
Spring框架的介绍和IoC入门
java·后端·spring
用户6151265617337 小时前
Java生态新纪元:虚拟线程、模式匹配与未来的编程范式
后端