在以前的Spring Boot基础教程系列中,已经经过《Spring Boot中使用@Async实现异步调用》一文介绍过如何使用
@Async
注解来实现异步调用了。可是,对于这些异步执行的控制是咱们保障自身应用健康的基本技能。本文咱们就来学习一下,若是经过自定义线程池的方式来控制异步调用的并发。java
本文中的例子咱们能够在以前的例子基础上修改,也能够建立一个全新的Spring Boot项目来尝试。git
第一步,先在Spring Boot主类中定义一个线程池,好比:github
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@EnableAsync
@Configuration
class TaskPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(200);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("taskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
}
复制代码
上面咱们经过使用ThreadPoolTaskExecutor
建立了一个线程池,同时设置了如下这些参数:spring
CallerRunsPolicy
策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;若是执行程序已关闭,则会丢弃该任务在定义了线程池以后,咱们如何让异步调用的执行任务使用这个线程池中的资源来运行呢?方法很是简单,咱们只须要在@Async
注解中指定线程池名便可,好比:springboot
@Slf4j
@Component
public class Task {
public static Random random = new Random();
@Async("taskExecutor")
public void doTaskOne() throws Exception {
log.info("开始作任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务一,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskTwo() throws Exception {
log.info("开始作任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务二,耗时:" + (end - start) + "毫秒");
}
@Async("taskExecutor")
public void doTaskThree() throws Exception {
log.info("开始作任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
log.info("完成任务三,耗时:" + (end - start) + "毫秒");
}
}
复制代码
最后,咱们来写个单元测试来验证一下bash
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private Task task;
@Test
public void test() throws Exception {
task.doTaskOne();
task.doTaskTwo();
task.doTaskThree();
Thread.currentThread().join();
}
}
复制代码
执行上面的单元测试,咱们能够在控制台中看到全部输出的线程名前都是以前咱们定义的线程池前缀名开始的,说明咱们使用线程池来执行异步任务的试验成功了!并发
2018-03-27 22:01:15.620 INFO 73703 --- [ taskExecutor-1] com.didispace.async.Task : 开始作任务一
2018-03-27 22:01:15.620 INFO 73703 --- [ taskExecutor-2] com.didispace.async.Task : 开始作任务二
2018-03-27 22:01:15.620 INFO 73703 --- [ taskExecutor-3] com.didispace.async.Task : 开始作任务三
2018-03-27 22:01:18.165 INFO 73703 --- [ taskExecutor-2] com.didispace.async.Task : 完成任务二,耗时:2545毫秒
2018-03-27 22:01:22.149 INFO 73703 --- [ taskExecutor-3] com.didispace.async.Task : 完成任务三,耗时:6529毫秒
2018-03-27 22:01:23.912 INFO 73703 --- [ taskExecutor-1] com.didispace.async.Task : 完成任务一,耗时:8292毫秒
复制代码
读者能够根据喜爱选择下面的两个仓库中查看Chapter4-1-3
项目:dom
若是您对这些感兴趣,欢迎star、follow、收藏、转发给予支持!异步