Springboot实现多线程及线程池监控

 更新时间:2024年01月31日 11:03:50   作者:i学无止境  
线程池的监控很重要,本文就来介绍一下Springboot实现多线程及线程池监控,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧

线程池的优点

  • 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗
  • 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行
  • 可以对线程做统一管理。

1.配置线程池

修改配置文件

# 异步线程配置
# 配置核心线程数
async:
  executor:
    thread:
      core_pool_size: 5 # 配置核心线程数
      max_pool_size: 5 # 配置最大线程数
      queue_capacity: 99999 # 配置队列大小
      name:
        prefix: async-service- # 配置线程池中的线程的名称前

线程池配置类

package com.bt.springboot.config;

import com.bt.springboot.task.ThreadPoolMonitor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zkx
 * @Date 2022/12/6 21:42
 */
@Slf4j
@Configuration
@EnableAsync
public class ExecutorConfig {

	@Value("${async.executor.thread.core_pool_size}")
	private int corePoolSize;
	@Value("${async.executor.thread.max_pool_size}")
	private int maxPoolSize;
	@Value("${async.executor.thread.queue_capacity}")
	private int queueCapacity;
	@Value("${async.executor.thread.name.prefix}")
	private String namePrefix;

	@Bean(name = "asyncServiceExecutor")
	public Executor asyncServiceExecutor() {
		log.info("start asyncServiceExecutor");
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		//配置核心线程数
		executor.setCorePoolSize(corePoolSize);
		//配置最大线程数
		executor.setMaxPoolSize(maxPoolSize);
		//配置队列大小
		executor.setQueueCapacity(queueCapacity);
		//配置线程池中的线程的名称前缀
		executor.setThreadNamePrefix(namePrefix);

		// rejection-policy:当pool已经达到max size的时候,如何处理新任务
		// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		//执行初始化
		executor.initialize();
		return executor;
	}
}

2.监控类

package com.bt.springboot.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: ChenBin
 */
@Slf4j
@Component
public class ThreadPoolMonitor extends ThreadPoolTaskExecutor {

	@Value("${async.executor.thread.name.prefix}")
	private String namePrefix;

	@Scheduled(cron = "0/1 * * * * ? ")
	private void showThreadPoolInfo() {
		ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
		if (namePrefix.equals(this.getThreadNamePrefix())){
			log.info("{} taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]",
					this.getThreadNamePrefix(),
					threadPoolExecutor.getTaskCount(),
					threadPoolExecutor.getCompletedTaskCount(),
					threadPoolExecutor.getActiveCount(),
					threadPoolExecutor.getQueue().size());
		}
	}
}

开启定时任务

在这里插入图片描述

3.修改线程池配置类

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

修改为ThreadPoolTaskExecutor executor = new ThreadPoolMonitor();

4.测试相关类

AsyncService

package com.bt.springboot.async;

/**
 * @author zkx
 * @Date 2022/12/6 21:47
 */
public interface AsyncService {

	/**
	 * 执行异步任务
	 * 可以根据需求,自己加参数拟定,我这里就做个测试演示
	 */
	void executeAsync();
}

AsyncServiceImpl

package com.bt.springboot.async.impl;

import com.bt.springboot.async.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author zkx
 * @Date 2022/12/6 21:48
 */
@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {



	@Override
	@Async("asyncServiceExecutor")
	public void executeAsync() {
		int i = 5;
		while(i > 0){
			i--;
			log.info("execute task");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				Thread.currentThread().interrupt();
			}
		}
	}
}

AsyncController

package com.bt.springboot.web.controller;

import com.bt.springboot.async.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zkx
 * @Date 2022/12/9 17:38
 */
@RestController
public class AsyncController {

	@Autowired
	private AsyncService asyncService;

	@GetMapping("/asyncTask")
	public void asyncTask(){
		asyncService.executeAsync();
	}
}

5.启动

1.执行任务前

2.执行任务

在这里插入图片描述

3.任务完成

在这里插入图片描述

到此这篇关于Springboot实现多线程及线程池监控的文章就介绍到这了,更多相关Springboot 多线程及线程池监控内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • Java中List的使用方法简单介绍

    Java中List的使用方法简单介绍

    这篇文章主要针对Java中List的使用方法为大家介绍了进行简单介绍,List是个集合接口,只要是集合类接口都会有个“迭代子”( Iterator ),利用这个迭代子,就可以对list内存的一组对象进行操作,感兴趣的小伙伴们可以参考一下
    2016-07-07
  • 详谈Java中的事件监听机制

    详谈Java中的事件监听机制

    下面小编就为大家带来一篇详谈Java中的事件监听机制。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • 详解spring cloud整合Swagger2构建RESTful服务的APIs

    详解spring cloud整合Swagger2构建RESTful服务的APIs

    这篇文章主要介绍了详解spring cloud整合Swagger2构建RESTful服务的APIs,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-01-01
  • PowerJob的GridFsManager工作流程源码解读

    PowerJob的GridFsManager工作流程源码解读

    这篇文章主要为大家介绍了PowerJob的GridFsManager工作流程源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2024-01-01
  • JNI语言基本知识

    JNI语言基本知识

    JNI是Java Native Interface的缩写,它提供了若干的API实现了Java和其他语言的通信(主要是C&C++)。接下来通过本文给大家分享jni 基础知识,感兴趣的朋友一起看看吧
    2017-10-10
  • JAVA IDEA项目打包为jar包的步骤详解

    JAVA IDEA项目打包为jar包的步骤详解

    在Java开发中我们通常会将我们的项目打包成可执行的Jar包,以便于在其他环境中部署和运行,下面这篇文章主要给大家介绍了关于JAVA IDEA项目打包为jar包的相关资料,需要的朋友可以参考下
    2024-08-08
  • springboot集成gzip和zip数据压缩传输(适用大数据信息传输)

    springboot集成gzip和zip数据压缩传输(适用大数据信息传输)

     在大数据量的传输中,压缩数据后进行传输可以一定程度的解决速度问题,本文主要介绍了springboot集成gzip和zip数据压缩传输,具有一定的参考价值,感兴趣的可以了解一下
    2023-09-09
  • Spring6整合JUnit的详细步骤

    Spring6整合JUnit的详细步骤

    这篇文章主要介绍了Spring6整合JUnit的详细步骤,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • Java中csv文件读写超详细分析

    Java中csv文件读写超详细分析

    CSV是一种通用的、相对简单的文件格式,其文件以纯文本形式存储表格数据,下面这篇文章主要给大家介绍了关于Java中csv文件读写分析的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • Springboot继承Keycloak实现单点登录与退出功能

    Springboot继承Keycloak实现单点登录与退出功能

    这篇文章主要介绍了Springboot继承Keycloak实现单点登陆与退出,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08

最新评论