在以前的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、收藏、轉發給予支持!異步