Spring Boot项目,可以用Spring提供的对ThreadPoolExecutor封装的线程池ThreadPoolTaskExecutor,直接使用注解启用
pom.xml依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 排除Logback日志框架 -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--log4j2 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- hutool工具类-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.5</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
添加配置类
先创建一个线程池的配置,让Spring Boot加载,用来定义如何创建一个ThreadPoolTaskExecutor,要使用@Configuration和@EnableAsync这两个注解,表示这是个配置类,并且是线程池的配置类
import com.songzixian.executor.VisiableThreadPoolTaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
/**
* <p>
* Description: 多线程配置类
* </p>
*
* @author songzixian
* @version v2.0.0
* @create 2021-05-25 11:30
* @see com.songzixian.config
*/
@Configuration
@EnableAsync
public class ExecutorConfig {
private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
@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;
@Value("${async.executor.thread.keep.alive}")
private int keepAlive;
@Bean(name = "asyncServiceExecutor") //这里的bean的name是什么,@Async的value就是写什么
public Executor asyncServiceExecutor() {
logger.info("start asyncServiceExecutor");
//ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(corePoolSize);
//配置最大线程数
executor.setMaxPoolSize(maxPoolSize);
//配置队列大小
executor.setQueueCapacity(queueCapacity);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix(namePrefix);
//许空闲时间,默认60
executor.setKeepAliveSeconds(keepAlive);
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
application
@Value是我配置在application.properties,可以参考配置,自由定义
# 异步线程配置
# 配置核心线程数
async.executor.thread.core_pool_size = 5
# 配置最大线程数
async.executor.thread.max_pool_size = 5
# 配置队列大小
async.executor.thread.queue_capacity = 99999
# 配置线程池中的线程的名称前缀
async.executor.thread.name.prefix = async-service-
# 许空闲时间,默认60
async.executor.thread.keep.alive = 60
Service接口
创建一个Service接口,是异步线程的接口
/**
* <p>
* Description: 异步线程接口
* </p>
*
* @author songzixian
* @version v2.0.0
* @create 2021-05-25 11:36
* @see com.songzixian.service
*/
public interface AsyncService {
/**
* 执行异步任务
* 可以根据需求,自己加参数拟定,我这里就做个测试演示
*/
void executeAsync();
}
多线程实现类
import com.songzixian.service.AsyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* <p>
* Description: 异步线程实现类
* </p>
*
* @author songzixian
* @version v2.0.0
* @create 2021-05-25 11:36
* @see com.songzixian.service.impl
*/
@Service
public class AsyncServiceImpl implements AsyncService {
private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);
@Override
@Async("asyncServiceExecutor") //value为多线程配置bean的名称
public void executeAsync() {
logger.info("start executeAsync");
System.out.println("异步调用方法1");
System.out.println("异步调用方法2");
logger.info("end executeAsync");
}
}
Service
将Service层的服务异步化,在executeAsync()方法上增加注解@Async("asyncServiceExecutor"),asyncServiceExecutor方法是前面ExecutorConfig.java中的方法名,表明executeAsync方法进入的线程池是asyncServiceExecutor方法创建的。
接下来就是在Controller里或者是哪里通过注解@Autowired注入这个Service
import com.songzixian.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* Description:
* </p>
*
* @author songzixian
* @version v2.0.0
* @create 2021-05-25 11:39
* @see com.songzixian.controller
*/
@RestController
public class TestAsyncController {
@Autowired
private AsyncService asyncService;
/**
* 调用多线程
*/
@GetMapping("/async")
public void async(){
asyncService.executeAsync();
}
}
用postmain或者其他工具来多次测试请求一下
2022-04-01 14:08:41.039 INFO 24512 --- [async-service-1] c.s.service.impl.AsyncServiceImpl : start executeAsync
异步调用方法1
异步调用方法2
2022-04-01 14:08:41.040 INFO 24512 --- [async-service-1] c.s.service.impl.AsyncServiceImpl : end executeAsync
2022-04-01 14:08:44.455 INFO 24512 --- [async-service-2] c.s.service.impl.AsyncServiceImpl : start executeAsync
异步调用方法1
异步调用方法2
2022-04-01 14:08:44.456 INFO 24512 --- [async-service-2] c.s.service.impl.AsyncServiceImpl : end executeAsync
2022-04-01 14:08:45.097 INFO 24512 --- [async-service-3] c.s.service.impl.AsyncServiceImpl : start executeAsync
异步调用方法1
异步调用方法2
2022-04-01 14:08:45.097 INFO 24512 --- [async-service-3] c.s.service.impl.AsyncServiceImpl : end executeAsync
道这里就已经完成整合了
完善
通过以上日志可以发现,[async-service-]是有多个线程的,显然已经在我们配置的线程池中执行了,并且每次请求中,controller的起始和结束日志都是连续打印的,表明每次请求都快速响应了,而耗时的操作都留给线程池中的线程去异步执行;
虽然我们已经用上了线程池,但是还不清楚线程池当时的情况,有多少线程在执行,多少在队列中等待呢?这里我创建了一个ThreadPoolTaskExecutor的子类,在每次提交线程的时候都会将当前线程池的运行状况打印出来
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
/**
* <p>
* Description:
* </p>
*
* @author songzixian
* @version v2.0.0
* @create 2021-05-25 11:44
* @see com.songzixian.executor
*/
public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
private static final Logger logger = LoggerFactory.getLogger(VisiableThreadPoolTaskExecutor.class);
private void showThreadPoolInfo(String prefix) {
ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
if (null == threadPoolExecutor) {
return;
}
logger.info("{}, {},taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]",
this.getThreadNamePrefix(),
prefix,
threadPoolExecutor.getTaskCount(),
threadPoolExecutor.getCompletedTaskCount(),
threadPoolExecutor.getActiveCount(),
threadPoolExecutor.getQueue().size());
}
@Override
public void execute(Runnable task) {
showThreadPoolInfo("1. do execute");
super.execute(task);
}
@Override
public void execute(Runnable task, long startTimeout) {
showThreadPoolInfo("2. do execute");
super.execute(task, startTimeout);
}
@Override
public Future<?> submit(Runnable task) {
showThreadPoolInfo("1. do submit");
return super.submit(task);
}
@Override
public <T> Future<T> submit(Callable<T> task) {
showThreadPoolInfo("2. do submit");
return super.submit(task);
}
@Override
public ListenableFuture<?> submitListenable(Runnable task) {
showThreadPoolInfo("1. do submitListenable");
return super.submitListenable(task);
}
@Override
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
showThreadPoolInfo("2. do submitListenable");
return super.submitListenable(task);
}
}
如上所示,showThreadPoolInfo方法中将任务总数、已完成数、活跃线程数,队列大小都打印出来了,然后Override了父类的execute、submit等方法,在里面调用showThreadPoolInfo方法,这样每次有任务被提交到线程池的时候,都会将当前线程池的基本情况打印到日志中;
修改ExecutorConfig.java的asyncServiceExecutor方法,将ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor()改为ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor()
@Bean(name = "asyncServiceExecutor")
public Executor asyncServiceExecutor() {
logger.info("start asyncServiceExecutor");
//在这里修改
ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
//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;
}
再次启动该工程测试
2022-04-01 14:12:55.888 INFO 16968 --- [nio-8080-exec-2] c.s.e.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [0], completedTaskCount [0], activeCount [0], queueSize [0]
2022-04-01 14:12:55.889 INFO 16968 --- [async-service-1] c.s.service.impl.AsyncServiceImpl : start executeAsync
异步调用方法1
异步调用方法2
2022-04-01 14:12:55.889 INFO 16968 --- [async-service-1] c.s.service.impl.AsyncServiceImpl : end executeAsync
2022-04-01 14:12:57.818 INFO 16968 --- [nio-8080-exec-3] c.s.e.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [1], completedTaskCount [1], activeCount [0], queueSize [0]
2022-04-01 14:12:57.818 INFO 16968 --- [async-service-2] c.s.service.impl.AsyncServiceImpl : start executeAsync
异步调用方法1
异步调用方法2
2022-04-01 14:12:57.818 INFO 16968 --- [async-service-2] c.s.service.impl.AsyncServiceImpl : end executeAsync
2022-04-01 14:14:06.617 INFO 16968 --- [nio-8080-exec-6] c.s.e.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [2], completedTaskCount [2], activeCount [0], queueSize [0]
2022-04-01 14:14:06.617 INFO 16968 --- [async-service-3] c.s.service.impl.AsyncServiceImpl : start executeAsync
异步调用方法1
异步调用方法2
2022-04-01 14:14:06.618 INFO 16968 --- [async-service-3] c.s.service.impl.AsyncServiceImpl : end executeAsync
注意这一行日志:
2021-05-25 14:14:06.617 INFO 16968 --- [nio-8080-exec-6] c.s.e.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [2], completedTaskCount [2], activeCount [0], queueSize [0]
这说明提交任务到线程池的时候,调用的是submit(Callable task)这个方法,当前已经提交了2个任务,完成了2个,当前有0个线程在处理任务,还剩0个任务在队列中等待,线程池的基本情况一路了然