SpringBoot框架@Async注解文章:SpringBoot异步调用@Async
SpringBoot线程池ThreadPoolExecutor文章:SpringBoot线程池ThreadPoolExecutor
ThreadPoolTaskExecutor是一个spring的线程池技术,其实,它的实现方式完全是使用ThreadPoolExecutor进行实现。
SpringBoot线程池ThreadPoolTaskExecutor代码实现
service层
- 创建一个service层的接口AsyncService,如下:
public interface AsyncService {
/**
* 执行异步任务
* */
void executeAsync();
}
- 对应的AsyncServiceImpl,实现如下:
import com.ceair.service.AsyncService;
import lombok.extern.java.Log;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* 异步线程service
* @author jeffrey_hjf
*/
@Service
@Log
public class AsyncServiceImpl implements AsyncService {
@Override
@Async("asyncServiceExecutor")
public void executeAsync() {
log.info("start executeAsync");
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
log.info("end executeAsync");
}
}
线程池配置
创建一个配置类ThreadPoolExecutorConfig,用来定义如何创建一个ThreadPoolTaskExecutor,要使用@Configuration和@EnableAsync这两个注解,表示这是个配置类,并且是线程池的配置类,如下所示:
@Configuration
//@EnableAsync //在启动类里面加了@EnableAsync标识,这里可以不加
@Log
public class ThreadPoolExecutorConfig {
@Value("${async.executor.thread.core_pool_size}")
private int corePoolSize = 5;
@Value("${async.executor.thread.max_pool_size}")
private int maxPoolSize = 5;
@Value("${async.executor.thread.queue_capacity}")
private int queueCapacity = 99999;
@Value("${async.executor.thread.name.prefix}")
private String namePrefix = "async-service-";
/**
* 异步线程池
*/
@Bean("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;
}
}
controller层
创建一个controller为Hello,里面定义一个http接口,做的事情是调用Service层的服务,如下:
/**
* @ClassName UserController
* @Author jeffrey_hjf
* @Description User
**/
@RestController
@RequestMapping("/api")
@Log
public class UserController {
@Autowired
private AsyncService asyncService;
/**
* 线程池测试入口
*/
@GetMapping("executeAsyncPool")
public String executeAsyncPool() {
log.info("start submit");
//调用service层的任务
asyncService.executeAsync();
log.info("end submit");
return "success";
}
}
执行效果
控制台看见日志如下:
2019-08-26 17:28:12.552 INFO 9024 --- [nio-9090-exec-1] com.ceair.controller.UserController : start submit
2019-08-26 17:28:12.558 INFO 9024 --- [nio-9090-exec-1] com.ceair.controller.UserController : end submit
2019-08-26 17:28:12.559 INFO 9024 --- [async-service-1] com.ceair.service.impl.AsyncServiceImpl : start executeAsync
2019-08-26 17:28:13.560 INFO 9024 --- [async-service-1] com.ceair.service.impl.AsyncServiceImpl : end executeAsync
如上日志所示,我们可以看到controller的执行线程是”nio-8080-exec-1”,这是tomcat的执行线程,而service层的日志显示线程名为“async-service-1”,显然已经在我们配置的线程池中执行了,并且每次请求中,controller的起始和结束日志都是连续打印的,表明每次请求都快速响应了,而耗时的操作都留给线程池中的线程去异步执行;
SpringBoot线程池扩展ThreadPoolTaskExecutor代码实现
虽然我们已经用上了线程池,但是还不清楚线程池当时的情况,有多少线程在执行,多少在队列中等待呢?这里我创建了一个ThreadPoolTaskExecutor的子类,在每次提交线程的时候都会将当前线程池的运行状况打印出来。
扩展ThreadPoolTaskExecutor类
import lombok.extern.java.Log;
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;
@Log
public class VisiableThreadPoolTaskExecutorConfig extends ThreadPoolTaskExecutor {
private void showThreadPoolInfo(String prefix){
ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
if(null==threadPoolExecutor){
return;
}
log.info(String.format("%s, %s,taskCount [%s], completedTaskCount [%s], activeCount [%s], queueSize [%s]",
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方法,这样每次有任务被提交到线程池的时候,都会将当前线程池的基本情况打印到日志中;
修改ThreadPoolExecutorConfig配置类
修改ThreadPoolExecutorConfig.java的asyncServiceExecutor方法,将ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor()改为ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor(),如下所示:
/**
* 线程池配置类
* @author jeffrey_hjf
*/
@Configuration
//@EnableAsync
@Log
public class ThreadPoolExecutorConfig {
@Value("${async.executor.thread.core_pool_size}")
private int corePoolSize = 5;
@Value("${async.executor.thread.max_pool_size}")
private int maxPoolSize = 5;
@Value("${async.executor.thread.queue_capacity}")
private int queueCapacity = 99999;
@Value("${async.executor.thread.name.prefix}")
private String namePrefix = "async-service-";
/**
* 异步线程池
*/
@Bean("asyncServiceExecutor")
public Executor asyncServiceExecutor() {
log.info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutorConfig();
//配置核心线程数
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;
}
}
执行效果
日志如下:
2019-08-26 17:55:22.091 INFO 15252 --- [nio-9090-exec-8] com.ceair.controller.UserController : start submit
2019-08-26 17:55:22.091 INFO 15252 --- [nio-9090-exec-8] c.c.VisiableThreadPoolTaskExecutorConfig : async-service-, 2. do submit,taskCount [5], completedTaskCount [2], activeCount [2], queueSize [1]
2019-08-26 17:55:22.092 INFO 15252 --- [nio-9090-exec-8] com.ceair.controller.UserController : end submit
2019-08-26 17:55:22.092 INFO 15252 --- [async-service-1] com.ceair.service.impl.AsyncServiceImpl : start executeAsync
2019-08-26 17:55:23.094 INFO 15252 --- [async-service-1] com.ceair.service.impl.AsyncServiceImpl : end executeAsync
这说明提交任务到线程池的时候,调用的是submit(Callable task)这个方法,当前已经提交了5个任务,完成了2个,当前有2个线程在处理任务,还剩1个任务在队列中等待,线程池的基本情况一路了然;
SpringBoot框架@Async注解文章:SpringBoot异步调用@Async
SpringBoot线程池ThreadPoolExecutor文章:SpringBoot线程池ThreadPoolExecutor