当前位置: 首页 > news >正文

springboot优雅停机无法关闭进程,kill无法停止springboot必须kill -9,springboot线程池使用

背景最近项目在jenkins部署的时候发现部署很慢,查看部署日志发现kill命令执行后应用pid还存在,导致必须在60秒等待期后kill -9杀死springboot进程

应用环境

  • springboot
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>2.6.3</version>
</dependency>
  • springcloud
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>2021.0.1.0</version><type>pom</type><scope>import</scope>
</dependency>
  • 监控
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId><version>2.6.3</version>
</dependency>

原因分析

  • 通过将全部日志调整为debug级别,观察到有个定时任务线程在不断执行,例子如下
@SpringBootApplication
@MapperScan("com.test.test.mapper")
public class TestApplication implements CommandLineRunner {static ScheduledExecutorService executor;public static void main(String[] args) {executor = Executors.newScheduledThreadPool(1);SpringApplication.run(TestApplication.class, args);}private static void run(ScheduledExecutorService executor) {executor.scheduleAtFixedRate(() -> {System.out.println("run");}, 0, 1, TimeUnit.SECONDS);@Overridepublic void run(String... args) throws Exception {run(executor);}
}

上述代码中,由于线程定义默认是非守护线程,执行优雅停机后,在用户线程停止后,非守护线程不会自动停止
在这里插入图片描述

在这里插入图片描述

解决办法

  1. 定义为守护线程
    对于非业务逻辑,例如监控数据上传,日志记录,这样做非常方便,但对于系统业务,这么做会导致未执行完成任务被丢弃。
  2. 将线程池定义为springbean,交予spring容器管理其生命周期
@SpringBootApplication
@MapperScan("com.test.test.mapper")
public class TestApplication implements CommandLineRunner {public static void main(String[] args) {SpringApplication.run(TestApplication.class, args);}private static void run(ScheduledExecutorService executor) {executor.scheduleAtFixedRate(() -> {System.out.println("run");}, 0, 1, TimeUnit.SECONDS);}@Beanpublic ScheduledExecutorService executor() {return Executors.newScheduledThreadPool(1);}@Overridepublic void run(String... args) throws Exception {ScheduledExecutorService executor = SpringUtil.getBean(ScheduledExecutorService.class);run(executor);}
}

效果
在这里插入图片描述弊端:此类方式中,由于线程池的工作线程属于非守护线程,应用会等待所有任务执行完成后才关闭。由于容器已经关闭,数据库连接池已经释放,这时候任务再获取spring容器内容会报错,因此这种方案只适用于用户日志记录,监控等非业务功能,效果如下:

@SpringBootApplication
@MapperScan("com.test.test.mapper")
@Slf4j
public class TestApplication implements CommandLineRunner {public static void main(String[] args) {SpringApplication.run(TestApplication.class, args);}private static void run(ExecutorService executor) {executor.execute(() -> {log.info("=====start");try {TimeUnit.SECONDS.sleep(25);User user = SpringUtil.getBean(IUserService.class).findById(10L);log.info("用户信息:" + user);} catch (Exception ex) {ex.printStackTrace();}log.info("=========end");});}@Beanpublic ExecutorService executor() {return new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS,new ArrayBlockingQueue<>(1),r -> {Thread thread =new Thread(r);return thread;},new ThreadPoolExecutor.DiscardOldestPolicy());}@Overridepublic void run(String... args) throws Exception {ExecutorService executor = SpringUtil.getBean(ExecutorService.class);run(executor);}
}

在这里插入图片描述

3.使用spring提供的ThreadPoolTaskExecutor线程池

@SpringBootApplication
@MapperScan("com.test.test.mapper")
@Slf4j
public class TestApplication implements CommandLineRunner {public static void main(String[] args) {SpringApplication.run(TestApplication.class, args);}private static void run(ThreadPoolTaskExecutor executor) {executor.execute(() -> {log.info("=====start");try {TimeUnit.SECONDS.sleep(25);User user = SpringUtil.getBean(IUserService.class).findById(10L);log.info("用户信息:" + user);} catch (Exception ex) {ex.printStackTrace();}log.info("=========end");});}@Beanpublic ThreadPoolTaskExecutor executor() {int core = Runtime.getRuntime().availableProcessors();ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(core > 3 ? core >> 1 : core);int maxSize = core + 2;executor.setMaxPoolSize(maxSize);//使用同步队列,避免任务进入等待队列排队导致耗时过长executor.setQueueCapacity(0);executor.setKeepAliveSeconds(30);executor.setWaitForTasksToCompleteOnShutdown(true);executor.setAwaitTerminationSeconds(25);executor.setThreadNamePrefix("async-");executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());executor.initialize();return executor;}@Overridepublic void run(String... args) throws Exception {ThreadPoolTaskExecutor executor = SpringUtil.getBean(ThreadPoolTaskExecutor.class);run(executor);}
}

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
从上图可以看到,应用会等待线程池任务执行完毕后才选择优雅关闭,因此对于异步业务任务,ThreadPoolTaskExecutor才是首选。
spring已经内置了ThreadPoolTaskExecutor 线程池实例,我们可以尝试修改其配置参数,简化代码来尝试,例如:
在这里插入图片描述

spring:task:execution:pool:queue-capacity: 0core-size: 2max-size: 16keep-alive: 30sthread-name-prefix: 'async-'shutdown:await-termination: trueawait-termination-period: 25s
@SpringBootApplication
@MapperScan("com.test.test.mapper")
@Slf4j
public class TestApplication implements CommandLineRunner {public static void main(String[] args) {SpringApplication.run(TestApplication.class, args);}private static void run(ThreadPoolTaskExecutor executor) {executor.execute(() -> {log.info("=====start");try {TimeUnit.SECONDS.sleep(25);User user = SpringUtil.getBean(IUserService.class).findById(10L);log.info("用户信息:" + user);} catch (Exception ex) {ex.printStackTrace();}log.info("=========end");});}@Overridepublic void run(String... args) throws Exception {ThreadPoolTaskExecutor executor = SpringUtil.getBean(ThreadPoolTaskExecutor.class);run(executor);}
}

效果与上述手动创建效果一样,但是内置的ThreadPoolTaskExecutor线程池无法通过配置修改拒绝策略rejectedExecutionHandler,队列满了之后默认是AbortPolicy,会丢弃加入的任务并抛异常,spring内置此线程池的初衷在于为定时任务使用,例如@Scheduled。
在这里插入图片描述
在这里插入图片描述

http://www.lryc.cn/news/437828.html

相关文章:

  • 【系统架构设计师-2015年真题】案例分析-答案及详解
  • MongoDB设置系统服务启动教程
  • mysql学习教程,从入门到精通,MySQL WHERE 子句(10)
  • 设计模式】Listener模式和Visitor模式的区别
  • 基于事件序列的数据获取
  • 太速科技-基于XC7Z100+AD9361的双收双发无线电射频板卡
  • 探索UWB技术的独特优势:实现高精度定位
  • 软件安装攻略:Sublime Text 下载安装和使用教程
  • ip地址为什么要轮换
  • C++ 继承【一篇让你学会继承】
  • DeviceNet网关HT3S-DNS-MDN读取七星华创CS310空气流量计数据应用案例
  • Smartbi体验中心新增系列Demo,用户体验更丰富
  • Kubernetes 与 springboot集成
  • 以太网传输出现不分包
  • [实践应用] 深度学习之激活函数
  • Java基础之数组
  • 基于SpringBoot+Vue的智慧自习室预约管理系统
  • pptpd配置文件/etc/pptpd.conf详解
  • springboot对数据库进行备份+对一个文件夹内的文件按时间排序,只保留最近的8个文件
  • 【软考中级攻略站】-软件设计师(4)-计算机网络基础
  • Android以及IoT设备传感器软件开发总结
  • Vue2/Vue3中编程式路由导航实践总结
  • 【nginx】ngx_http_proxy_connect_module 正向代理
  • 单考一个OCP认证?还是OCP和OCM认证都要考?
  • 在Spring官网查看Springboot与Java的版本对应关系
  • HarmonyOS学习(十二)——数据管理(一)分布式数据
  • 3D GS 测试自己的数据
  • 攻防世界 supersqli
  • OceanBase 运维管理工具 OCP 4.x 升级:聚焦高可用、易用性及可观测性
  • HarmonyOS应用开发( Beta5.0)HOS-用户认证服务:面部识别