Springboot中使用线程池的三种方式
前言
- 多线程是每个程序员的噩梦,用得好可以提升效率很爽,用得不好就是埋汰的火葬场。
- 这里不深入介绍,主要是讲解一些标准用法,熟读唐诗三百首,不会作诗也会吟。
- 这里就介绍一下springboot中的多线程的使用,使用线程连接池去异步执行业务方法。
- 由于代码中包含详细注释,也为了保持文章的整洁性,我就不过多的做文字描述了。
VisiableThreadPoolTaskExecutor 编写
- new VisiableThreadPoolTaskExecutor() 方式创建线程池, 返回值是 Executor
点击查看代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author love ice
* @create 2023-09-19 0:17
*/
@Slf4j
public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
@Override
public void execute(Runnable task){
showThreadPoolInfo("execute一个参数的方法执行");
}
@Override
public void execute(Runnable task, long startTimeout){
showThreadPoolInfo("execute两个参数的方法执行");
}
@Override
public Future<?> submit(Runnable task){
showThreadPoolInfo("submit Runnable task 入参方法执行");
return super.submit(task);
}
@Override
public <T> Future<T> submit(Callable<T> task){
showThreadPoolInfo("submit Callable<T> task 入参方法执行");
return super.submit(task);
}
@Override
public ListenableFuture<?> submitListenable(Runnable task){
showThreadPoolInfo("submitListenable(Runnable task) 方法执行");
return super.submitListenable(task);
}
@Override
public <T>ListenableFuture<T> submitListenable(Callable<T> task){
showThreadPoolInfo("submitListenable(Callable<T> task) 方法执行");
return super.submitListenable(task);
}
private void showThreadPoolInfo(String prefix){
ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
log.info("{}, {}, taskCount[{}], completedTaskCount[{}], activeCount[{}], queueSize[{}]",
this.getThreadNamePrefix(), prefix, threadPoolExecutor.getTaskCount(),
threadPoolExecutor.getCompletedTaskCount(), threadPoolExecutor.getActiveCount(),
threadPoolExecutor.getQueue().size());
}
}
ThreadExceptionLogHandler 编写
- 主要用于线程池出现异常时的捕获
点击查看代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author love ice
* @create 2023-09-19 0:13
*/
@Slf4j
@Component
public class ThreadExceptionLogHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("[{}]线程池异常,异常信息为:{}",t.getName(),e.getMessage(),e);
}
}
ExecutorConfig 编写
- 核心配置类
点击查看代码
import com.test.redis.Infrastructure.handler.ThreadExceptionLogHandler;
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 线程池配置
*
* @author love ice
* @create 2023-09-19 0:09
*/
@Configuration
@EnableAsync
public class ExecutorConfig {
@Value("${thread.pool.coreSize:50}")
private int coreSize;
@Value("${thread.pool.maxSize:50}")
private int maxSize;
@Value("${thread.pool.queueSize:9999}")
private int queueSize;
@Value("${thread.pool.threadNamePrefix:thread-name}")
private String threadNamePrefix;
@Value("${thread.pool.keepAlive:60}")
private int keepAlive;
@Autowired
private ThreadExceptionLogHandler threadExceptionLogHandler;
/**
* 方式一: new VisiableThreadPoolTaskExecutor() 方式创建线程池,返回值是 Executor
* 适用于 @Async("asyncServiceExecutor") 注解
* 也可以
* @Autowired
* private Executor asyncServiceExecutor;
*
* @return Executor
*/
@Bean
public Executor asyncServiceExecutor() {
VisiableThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
// 配置核心线程数 50
executor.setCorePoolSize(coreSize);
// 配置最大线程数 50
executor.setMaxPoolSize(maxSize);
// 配置队列大小 9999
executor.setQueueCapacity(queueSize);
// 配置线程池中的线程名称前缀 模块-功能-作用
executor.setThreadNamePrefix(threadNamePrefix);
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
// 线程池无法接受新的任务并且队列已满时,如果有新的任务提交给线程池,而线程池已经达到了最大容量限制,那么这个任务不会被丢弃,而是由调用该任务的线程来执行。
// 这样可以避免任务被直接丢弃,并让调用者自己执行任务以减轻任务提交频率。
// 这个拒绝策略可能会导致任务提交者的线程执行任务,这可能会对调用者的性能产生一些影响,因为调用者线程需要等待任务执行完成才能继续进行其他操作。
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 线程空闲后的最大存活时间 60
executor.setKeepAliveSeconds(keepAlive);
// 执行初始化
executor.initialize();
return executor;
}
/**
* 方式二: new ThreadPoolExecutor() 方式创建线程池
* 适用于:
* @Autowired
* private ExecutorService fbWorkerPool;
* @return ExecutorService
*/
@Bean
public ExecutorService workerPool() {
return new ThreadPoolExecutor(coreSize, maxSize, keepAlive, TimeUnit.MILLISECONDS,
new LinkedBlockingDeque<>(20000),
new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, threadNamePrefix + threadNumber.getAndIncrement());
thread.setUncaughtExceptionHandler(threadExceptionLogHandler);
return thread;
}
});
}
}
ExecutorController 编写
- 演示demo,三种不同的用法, 足以涵盖大部分场景
点击查看代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
/**
* 这里是demo演示、把业务写在 controller 了,一般开发都是在 service 层实现的。
*
* @author love ice
* @create 2023-09-19 0:59
*/
@RestController
@RequestMapping("/executor")
public class ExecutorController {
/**
* demo1: 使用异步注解 @Async("asyncServiceExecutor") 执行方法,适用于没有返回值的情况下
*/
public void asyncDemo1() {
// 假设这是从数据库查询出来的数据
List<String> nameList = new ArrayList<>(Arrays.asList("张三", "李四", "王五"));
// 把 nameList 进行切分
int j = 0, size = nameList.size(), batchSize = 10;
List<List<String>> list = new ArrayList<>();
while (j < size) {
List<String> batchList = nameList.stream().skip(j).limit(Math.min(j + batchSize, size) - j).collect(Collectors.toList());
list.add(batchList);
j += batchSize;
}
// 先把 list 切分成小份数据,在使用 @Async(),异步处理数据
list.stream().parallel().forEach(this::asynchronousAuthorization1);
}
/**
* 异步注解处理业务逻辑,实际业务开发,需要提取到 Service 层,否则会报错。
*
* @param paramList 入参
*/
@Async("asyncServiceExecutor")
public void asynchronousAuthorization1(List<String> paramList) {
paramList.forEach(System.out::println);
System.out.println("异步执行 paramList 业务逻辑");
}
//================================分隔符======================
@Autowired
private ExecutorService workerPool;
/**
* demo2: workerPool.execute() 实现异步逻辑。适用于没有返回值的情况下
*/
public void asyncDemo2() {
// 假设这是从数据库查询出来的数据
List<String> nameList = new ArrayList<>(Arrays.asList("张三", "李四", "王五"));
// 把 nameList 进行切分
int j = 0, size = nameList.size(), batchSize = 10;
List<List<String>> list = new ArrayList<>();
while (j < size) {
List<String> batchList = nameList.stream().skip(j).limit(Math.min(j + batchSize, size) - j).collect(Collectors.toList());
list.add(batchList);
j += batchSize;
}
// 将 list 切分成小份数据,workerPool.execute(),异步处理数据
list.stream().parallel().forEach(paramList->{
workerPool.execute(()->asynchronousAuthorization2(paramList));
});
}
public void asynchronousAuthorization2(List<String> paramList) {
paramList.forEach(System.out::println);
System.out.println("异步执行 paramList 业务逻辑");
}
//================================分隔符======================
/**
* demo3: futures.add() 实现异步逻辑。适用于有返回值的情况下
*/
public void asyncDemo3() {
// 假设这是从数据库查询出来的数据
List<String> nameList = new ArrayList<>(Arrays.asList("张三", "李四", "王五"));
// 把 nameList 进行切分
int j = 0, size = nameList.size(), batchSize = 10;
List<List<String>> list = new ArrayList<>();
while (j < size) {
List<String> batchList = nameList.stream().skip(j).limit(Math.min(j + batchSize, size) - j).collect(Collectors.toList());
list.add(batchList);
j += batchSize;
}
List<CompletableFuture<String>> futures = new ArrayList<>();
// 将 list 切分成小份数据,futures.add(),异步处理数据,有返回值的情况下
list.forEach(paramList->{
// CompletableFuture.supplyAsync() 该任务会在一个新的线程中执行,并返回一个结果
// 通过futures.add(...)将这个异步任务添加到futures列表中。这样可以方便后续对多个异步任务进行管理和处理
futures.add(CompletableFuture.supplyAsync(() -> {
asynchronousAuthorization3(paramList);
return "默认值";
}, workerPool));
// 防止太快,让它休眠一下
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
//new CompletableFuture[0] 创建了一个初始长度为 0 的 CompletableFuture 数组,作为目标数组。然后,futures.toArray(new CompletableFuture[0]) 将 futures 列表中的元素复制到目标数组中,并返回结果数组。
CompletableFuture<String>[] futuresArray = futures.toArray(new CompletableFuture[0]);
// 通过将多个异步任务添加到futures列表中,我们可以使用CompletableFuture提供的方法来对这些异步任务进行组合、等待和处理。
// 例如使用CompletableFuture.allOf(...)等待所有任务完成,或者使用CompletableFuture.join()获取单个任务的结果等。
CompletableFuture.allOf(futures.toArray(futuresArray)).join();
// 获取每个任务的结果或处理异常
List<String> results = new ArrayList<>();
for (CompletableFuture<String> future :futuresArray) {
// 处理任务的异常
future.exceptionally(ex -> {
System.out.println("Task encountered an exception: " + ex.getMessage());
return "0"; // 返回默认值或者做其他补偿操作
});
// 获取任务结果
String result = future.join();
results.add(result);
}
// 所有任务已完成,可以进行下一步操作
}
public void asynchronousAuthorization3(List<String> paramList) {
paramList.forEach(System.out::println);
System.out.println("异步执行 paramList 业务逻辑");
}
}
Springboot中使用线程池的三种方式的更多相关文章
- Spring boot 梳理 - SpringBoot中注入ApplicationContext对象的三种方式
直接注入(Autowired) @Configuration public class OAConfig { @Autowired private ApplicationContext applica ...
- SpringBoot中注入ApplicationContext对象的三种方式
[本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究.若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!] 在项目中,我们可 ...
- java核心知识点学习----创建线程的第三种方式Callable和Future CompletionService
前面已经指出通过实现Runnable时,Thread类的作用就是将run()方法包装成线程执行体,那么是否可以直接把任意方法都包装成线程执行体呢?Java目前不行,但其模仿者C#中是可以的. Call ...
- IOS 多线程,线程同步的三种方式
本文主要是讲述 IOS 多线程,线程同步的三种方式,更多IOS技术知识,请登陆疯狂软件教育官网. 一般情况下我们使用线程,在多个线程共同访问同一块资源.为保护线程资源的安全和线程访问的正确性. 在IO ...
- java核心知识点----创建线程的第三种方式 Callable 和 Future CompletionService
前面已经指出通过实现Runnable时,Thread类的作用就是将run()方法包装成线程执行体,那么是否可以直接把任意方法都包装成线程执行体呢?Java目前不行,但其模仿者C#中是可以的. Call ...
- 在Tomcat中部署web项目的三种方式
搬瓦工搭建SS教程 SSR免费节点:http://www.xiaokeli.me 在这里介绍在Tomcat中部署web项目的三种方式: 1.部署解包的webapp目录 2.打包的war文件 3.Man ...
- Tomcat中部署web应用的三种方式
Tomcat中部署web应用的三种方式(静态部署) 第一种,针对war或解压后的war,最为常用的是直接操作webapp目录,将完整的war包或者web应用直接放到webapp目录下.使用 ...
- spring中创建bean对象的三种方式以及作用范围
时间:2020/02/02 一.在spring的xml配置文件中创建bean对象的三种方式: 1.使用默认构造函数创建.在spring的配置文件中使用bean标签,配以id和class属性之后,且没有 ...
- JAVA中创建线程池的五种方法及比较
之前写过JAVA中创建线程的三种方法及比较.这次来说说线程池. JAVA中创建线程池主要有两类方法,一类是通过Executors工厂类提供的方法,该类提供了4种不同的线程池可供使用.另一类是通过Thr ...
- Java 实现线程安全的三种方式
一个程序在运行起来的时候会转换成进程,通常含有多个线程. 通常情况下,一个进程中的比较耗时的操作(如长循环.文件上传下载.网络资源获取等),往往会采用多线程来解决. 比如显示生活中,银行取钱问题.火车 ...
随机推荐
- SpringBoot配置文件加载
Spring Boot 配置文件加载是通过 Spring Boot 的自动配置机制实现的,它可以根据不同的环境加载不同的配置文件,包括 application.properties.applicati ...
- SQL后半部和JDBC
SQL后半部 排序order by asc 升序desc 降序select *from 表名 order by 列名 asc ; select *from 表名 order by 列名 asc , 列 ...
- 【C#/.NET】xUnit和Moq实现TDD
目录 前置条件 Moq xUnit TDD 实践 创建项目 红灯 绿灯 重构 单元测试一些最佳实践 总结 前置条件 Moq 安装Moq包 Install-Package Moq Moq是一个Mo ...
- 【快应用】addEventListener()方法无法监听动画事件
[关键词] 动画监听.动态改变 [问题背景] Style中设置动画样式,然后在onshow生命周期中调用addEventListener()方法去监听动画事件,无法监听到,该方法无任何回调返回 问题 ...
- Python运维开发之路《WEB框架:Django》
一.Web框架的本质 所有的web框架.web请求:本质上都是:socket 浏览器:socket客户端 服务器:socket服务端 1. socket服务端 import socket def ha ...
- PHP支付接口签名生成数据
<?php //作者主页 https://www.woailunwen.com $pay_memberid = '商户号'; $pay_orderid = '订单号'; $pay_amount ...
- 浅析switch和if(开发中这两者的优缺点;分析出优缺点在使用就能更确定自己需要使用哪个函数了)
分析 Switch 相较于 if 的优点 1.switch 执行效率 高于 if 的执行效率 分析: switch是在编译阶段将子函数的地址和判断条件绑定了,只要直接将a的直接映射到子函数地址去执 ...
- 技术选型|K歌App中的实时合唱如何进行选型
摘要 在线K歌软件的开发有许多技术难点,需考虑到音频录制和处理.实时音频传输和同步.音频压缩和解压缩.设备兼容性问题等技术难点外,此外,开发者还应关注音乐版权问题,确保开发的应用合规合法. 前言 前面 ...
- 刷了一个月AI歌唱的视频 做一个大胆预测
现在的AI热点转到ChatAI和AI唱歌去了 很好理解(现在每天在看Neuro的切片 感慨这才是看V的初心 可惜Neuro这个形象在创立的时候只是一个ChatAI 和游戏用的GameBOT并不是同一个 ...
- C#选择排序(Selection Sort)算法
选择排序原理介绍 选择排序(Selection Sort)是一种简单的排序算法,其实现原理如下: 遍历待排序数组,从第一个元素开始. 假设当前遍历的元素为最小值,将其索引保存为最小值索引(minInd ...