首页 > 其他分享 >springboot 线程池的使用

springboot 线程池的使用

时间:2022-11-03 10:42:04浏览次数:56  
标签:springboot org AsyncConfigurer springframework 线程 使用 taskExecutor import


线程池可以用于解决单线程干某件事情比较慢的问题

AsyncConfigurer:通过实现AsyncConfigurer自定义线程池,包含异常处理
实现AsyncConfigurer接口对异常线程池更加细粒度的控制

步骤:*
a) 创建线程自己的线程池
b) 对void方法抛出的异常处理的类AsyncUncaughtExceptionHandler

demo

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
* @author
* @version 1.0
* <p>
* 配置类实现AsyncConfigurer接口并重写getAsyncExecutor方法,并返回ThreadPoolTaskExecutor,
* 这样我们就获得了一个基于线程池TaskExecutor
*/
@Configuration
@ComponentScan("com.demo") //扫描一定要包含执行类
@EnableAsync
@PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true)//手动配置目录,解决property配置找不到的问题
public class ThreadConfig implements AsyncConfigurer {

@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//核心线程数
taskExecutor.setCorePoolSize(20);
//队列最大长度
taskExecutor.setQueueCapacity(1000);
//最大线程数
taskExecutor.setMaxPoolSize(50);
//线程池维护线程所允许的空闲时间(单位秒)
taskExecutor.setKeepAliveSeconds(10);
//设置名称
taskExecutor.setThreadNamePrefix("demo-thread");
/*
* 线程池对拒绝任务(无线程可用)的处理策略
* ThreadPoolExecutor.CallerRunsPolicy策略,调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
*/
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SpringAsyncExceptionHandler();
}
class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
System.out.println("线程池错误!" + throwable.getMessage());
}
}
}

线程池批量调用待执行任务对任务进行并发执行:

ExecutorService pool = Executors.newFixedThreadPool(webProcessInfo.getMaxThread());
List<Callable<Integer>> callers = new ArrayList<>();
callers.add(()->{
crawlParseService.getChildUrls(linkurl, projectId, batchId, baseUrl, webProcessInfo, uncheckedUrlSet);
return null;
});

//用线程池来执行callers中的批量任务
try {
pool.invokeAll(callers);
pool.shutdown();
}catch (InterruptedException e){
e.printStackTrace();
}

以上


标签:springboot,org,AsyncConfigurer,springframework,线程,使用,taskExecutor,import
From: https://blog.51cto.com/u_14196886/5819047

相关文章

  • cloud stream 使用案例
    实现生产者发送消息,消费者接收消息的demo在你的项目中加入<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-stream-ra......
  • java 简单使用线程池
    定义一个ThreadPoolExecutorprivatefinalBlockingQueue<Runnable>taskQueue=newLinkedBlockingDeque<>();privatefinalThreadPoolExecutorexecutor=newThreadPo......
  • springboot @SessionAttributes
    服务器token//User.javapublicclassUser{privateStringemail;privateStringuserName;privateIntegeruserId;privateStringmobile;publicSt......
  • springboot javax.servlet.Filter使用
    请求拦截器优点:1、拦截非法请求重定向2、验证用户token下面是demo程序,有问题的可以在评论区留言@WebFilter(filterName="authenticationFilter",urlPatterns={"/user/*......
  • 查看mysql资源使用情况
    usesysselectevent_name,current_allocfromsys.memory_global_by_current_byteslimit10;selecthost,current_allocatedfrommemory_by_host_by_current_byte......
  • 【c&c++】 cjson使用_Keil环境下Jansson解析库的使用——基于STM32F103
    前言之前我曾经写过几个JSON解析库的使用方法:Qt平台下使用QJson解析和构建JSON字符串使用cJSON库解析JSON使用cJSON库构建JSON对于嵌入式开发,比较常用的就是cJSON解析......
  • 转载文章 c++调用yolov4模型进行目标检测-使用yolov4官方接口
    前言yolo系列用c写的,在工程中的部署特别方便。4月份yolov4横空出世,之前试了试效果,精度确实有了很大的提升,AB大神nb。最近需要在C++项目中使用yolov4,尝试了opencv的调用(见......
  • 实例034 使用goto语句在数组中搜索指定图书
      usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usi......
  • 【c&c++】[C++]使用Jansson生成与解析json字符串
    安装配置序列化与反序列化生成Json解析JsonJansson是一个用于解码、编码、操控JSON的C库:简单直观的API和数据模型没有依赖项完整的Unicode支持(UTF-8)安装 ......
  • c# winform使用NOPI读取Excel读取图片
    需求:在Winform使用NOPI做导入时候,需要导入数据的同时导入图片。虽然代码方面不适用(我好像也没仔细看过代码),但是感谢大佬给了灵感http://www.wjhsh.net/IT-Ramon-p-13100......