Java多線程開發系列之五:Springboot 中異步請求方法的使用

Springboot 中異步線程的使用
在過往的後臺開發中,我們往往使用java自帶的線程或線程池,來進行異步的調用。這對於效果來說沒什麼,甚至可以讓開發人員對底層的狀況更清晰,但是對於代碼的易讀性和可維護性卻非常的差。
開發人員在實際使用過程中,應該更多的將精力放置在業務代碼的書寫過程中,而不是系統代碼的維護中。你需要懂,但是不需要你直接維護去寫,這纔是編程語言的風向標。(這也是爲什麼spring在目前的java開發中,佔用比重如此之大的原因之一)(防盜連接:本文首發自http://www.cnblogs.com/jilodream/ )
下面來看使用Springboot 來實現異步調用的集中場景
一、簡易註解,無需額外配置
1、添加@EnableAsync 到啓動類(或者線程池配置類中)
2、添加@Async到需要異步執行的方法中
代碼如下:

啓動類

1 @EnableAsync
2 @SpringBootApplication
3 public class DemoLearnSpringbootApplication {
4 
5     public static void main(String[] args) {
6         SpringApplication.run(DemoLearnSpringbootApplication.class, args);
7     }
8 }

調用類

 1 @Component
 2 public class SimpleAsyncDemo {
 3     @Autowired
 4     private SimpleTaskHandler simpleTaskHandler;
 5 
 6 
 7     @PostConstruct
 8     public void execTaskHandler1() {
 9         try {
10             simpleTaskHandler.handle1(2);
11             simpleTaskHandler.handle2(2);
12             simpleTaskHandler.handle3(2);
13             simpleTaskHandler.handle1(2);
14             simpleTaskHandler.handle2(2);
15             simpleTaskHandler.handle3(2);
16             simpleTaskHandler.handle1(2);
17             simpleTaskHandler.handle2(2);
18             simpleTaskHandler.handle3(2);
19         } catch (InterruptedException e) {
20             e.printStackTrace();
21         }
22     }
23   
24 }

被異步調用的類

 1 @Component
 2 public class SimpleTaskHandler {
 3 
 4     public void printCurrentTime(String key) {
 5         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 6         System.out.println(format.format(new Date()) + "***" + key + "****" + Thread.currentThread().getName());
 7     }
 8 
 9     @Async
10     public void handle1(int time) throws InterruptedException {
11         TimeUnit.SECONDS.sleep(time);
12         printCurrentTime("handle1");
13     }
14 
15     @Async
16     public void handle2(int time) throws InterruptedException {
17         TimeUnit.SECONDS.sleep(time);
18         printCurrentTime("handle2");
19     }
20 
21     @Async
22     public void handle3(int time) throws InterruptedException {
23         TimeUnit.SECONDS.sleep(time);
24         printCurrentTime("handle3");
25     }
26 
27 
28 }

 

執行結果

handle1、handle2、handle3的執行結果爲亂序,不可預估。這樣最簡易的通過2個註解即完成異步線程的調用了。
細心的同學已經發現了,連續調用9次異步線程後,最後一次的線程名稱就會與之前的重複。這是由於默認的線程池配置的結果。

默認配置如下

# 核心線程數
spring.task.execution.pool.core-size=8  
# 最大線程數
spring.task.execution.pool.max-size=16
# 空閒線程存活時間
spring.task.execution.pool.keep-alive=60s
# 是否允許核心線程超時
spring.task.execution.pool.allow-core-thread-timeout=true
# 線程隊列數量
spring.task.execution.pool.queue-capacity=100
# 線程關閉等待
spring.task.execution.shutdown.await-termination=false
spring.task.execution.shutdown.await-termination-period=
# 線程名稱前綴
spring.task.execution.thread-name-prefix=task-

二、自定義線程池
只通過註解來完成異步線程調用,簡單明瞭,對應的異步線程來自springboot 默認生成的異步線程池。但是有些場景卻並不滿足。所以我們需要針對業務需要定義自己的線程池配置文件(防盜連接:本文首發自http://www.cnblogs.com/jilodream/ )
1、在application.properties中定義我們自己的線程池配置
2、在springboot項目中,添加對應的線程池bean對象
3、添加@EnableAsync 到啓動類(或者線程池配置類中)
4、添加@Async到需要異步執行的方法中
代碼如下:

application.properties配置文件

task.pool.demo.corePoolSize= 5
task.pool.demo.maxPoolSize= 10
task.pool.demo.keepAliveSeconds= 300
task.pool.demo.queueCapacity= 50

 

調用類

 1 @Component
 2 public class SimpleAsyncDemo {
 3 
 4     @Autowired
 5     private PoolTaskHandler poolTaskHandler;
 6 
 7 
 8     @PostConstruct
 9     public void execTaskHandler2() {
10         try {
11             poolTaskHandler.handle1(2);
12             poolTaskHandler.handle2(2);
13             poolTaskHandler.handle3(2);
14             poolTaskHandler.handle1(2);
15             poolTaskHandler.handle2(2);
16             poolTaskHandler.handle3(2);
17             poolTaskHandler.handle1(2);
18             poolTaskHandler.handle2(2);
19             poolTaskHandler.handle3(2);
20         } catch (InterruptedException e) {
21             e.printStackTrace();
22         }
23     }
24 
25 }

 

異步線程池的配置類

 1 @Configuration
 2 public class ThreadPoolConfig {
 3 
 4     @Value("${task.pool.demo.corePoolSize}")
 5     private int corePoolSize;
 6     @Value("${task.pool.demo.maxPoolSize}")
 7     private int maxPoolSize;
 8     @Value("${task.pool.demo.queueCapacity}")
 9     private int queueCapacity;
10     @Value("${task.pool.demo.keepAliveSeconds}")
11     private int keepAliveSeconds;
12 
13 
14     @Bean("handleAsync")
15     public TaskExecutor taskExecutor() {
16         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
17         // 設置核心線程數
18         executor.setCorePoolSize(corePoolSize);
19         // 設置最大線程數
20         executor.setMaxPoolSize(maxPoolSize);
21         // 設置隊列容量
22         executor.setQueueCapacity(queueCapacity);
23         // 設置線程活躍時間(秒)
24         executor.setKeepAliveSeconds(keepAliveSeconds);
25         // 設置默認線程名稱前綴
26         executor.setThreadNamePrefix("Thread-ABC-");
27         // 設置拒絕策略
28         executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
29         // 等待所有任務結束後再關閉線程池
30         executor.setWaitForTasksToCompleteOnShutdown(true);
31         return executor;
32     }
33 }

 

被異步調用的類

 1 @Component
 2 public class PoolTaskHandler {
 3 
 4     public void printCurrentTime(String key) {
 5         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 6         System.out.println(format.format(new Date()) + "***" + key + "****" + Thread.currentThread().getName());
 7     }
 8 
 9     @Async("handleAsync")
10     public void handle1(int time) throws InterruptedException {
11         TimeUnit.SECONDS.sleep(time);
12         printCurrentTime("handle-1");
13     }
14 
15     @Async("handleAsync")
16     public void handle2(int time) throws InterruptedException {
17         TimeUnit.SECONDS.sleep(time);
18         printCurrentTime("handle-2");
19     }
20 
21     @Async("handleAsync")
22     public void handle3(int time) throws InterruptedException {
23         TimeUnit.SECONDS.sleep(time);
24         printCurrentTime("handle-3");
25     }
26 
27 
28 }

執行結果如下

與上例類似,我們發現請求線程變成了每5個一批,這與我們在配置文件中的配置互相印證

調用類

 1 @Component
 2 public class SimpleAsyncDemo {
 3 
 4     @Autowired
 5     private ReturnTaskHandler returnTaskHandler;
 6 
 7     @PostConstruct
 8     public void execTaskHandler3() {
 9         try {
10             String a1 = returnTaskHandler.handle1(2);
11             String a2 = returnTaskHandler.handle2(2);
12             String a3 = returnTaskHandler.handle3(2);
13             String a4 = returnTaskHandler.handle1(2);
14             String a5 = returnTaskHandler.handle2(2);
15             String a6 = returnTaskHandler.handle3(2);
16             String a7 = returnTaskHandler.handle1(2);
17             String a8 = returnTaskHandler.handle2(2);
18             String a9 = returnTaskHandler.handle3(2);
19             int c = 1;
20         } catch (InterruptedException e) {
21             e.printStackTrace();
22         }
23     }
24 
25 }

被調用類

 1 @Component
 2 public class ReturnTaskHandler {
 3 
 4     public void printCurrentTime(String key) {
 5         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 6         System.out.println(format.format(new Date()) + "***" + key + "****" + Thread.currentThread().getName());
 7     }
 8 
 9     @Async("handleAsync")
10     public String handle1(int time) throws InterruptedException {
11         TimeUnit.SECONDS.sleep(time);
12         printCurrentTime("handle-1");
13         return "result1";
14     }
15 
16     @Async("handleAsync")
17     public String handle2(int time) throws InterruptedException {
18         TimeUnit.SECONDS.sleep(time);
19         printCurrentTime("handle-2");
20         return "result2";
21     }
22 
23     @Async("handleAsync")
24     public String handle3(int time) throws InterruptedException {
25         TimeUnit.SECONDS.sleep(time);
26         printCurrentTime("handle-3");
27         return "result3";
28     }
29 
30 }

其餘代碼繼續我們使用上文中的其他代碼
結果如下

所有結果返回都是null值。
如果想要拿到正確的執行結果,我們需要使用future接口類看來幫忙接住異步線程的返回結果(關於future等接口類的內容我會在後邊的文章中講解)
其餘代碼繼續我們使用上文中的其他代碼,改動的代碼如下:(防盜連接:本文首發自http://www.cnblogs.com/jilodream/ )
被調用類

 1 @Component
 2 public class ReturnSuccTaskHandler {
 3 
 4     public void printCurrentTime(String key) {
 5         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 6         System.out.println(format.format(new Date()) + "***" + key + "****" + Thread.currentThread().getName());
 7     }
 8 
 9     @Async("handleAsync")
10     public Future<String> handle1(int time) throws InterruptedException {
11         TimeUnit.SECONDS.sleep(time);
12         printCurrentTime("handle-1");
13         return new AsyncResult<>("result1");
14     }
15 
16     @Async("handleAsync")
17     public Future<String> handle2(int time) throws InterruptedException {
18         TimeUnit.SECONDS.sleep(time);
19         printCurrentTime("handle-2");
20         return new AsyncResult<>("result2");
21     }
22 
23     @Async("handleAsync")
24     public Future<String> handle3(int time) throws InterruptedException {
25         TimeUnit.SECONDS.sleep(time);
26         printCurrentTime("handle-3");
27         return new AsyncResult<>("result3");
28     }
29 
30 
31 }

調用類

 1 @Component
 2 public class SimpleAsyncDemo {
 3 
 4 
 5     @Autowired
 6     private ReturnSuccTaskHandler returnSuccTaskHandler;
 7 
 8 
 9 
10     @PostConstruct
11     public void execTaskHandler4() {
12         try {
13             Future<String> a1 = returnSuccTaskHandler.handle1(2);
14             Future<String> a2 = returnSuccTaskHandler.handle2(2);
15             Future<String> a3 = returnSuccTaskHandler.handle3(2);
16             Future<String> a4 = returnSuccTaskHandler.handle1(2);
17             Future<String> a5 = returnSuccTaskHandler.handle2(2);
18             Future<String> a6 = returnSuccTaskHandler.handle3(2);
19             Future<String> a7 = returnSuccTaskHandler.handle1(2);
20             Future<String> a8 = returnSuccTaskHandler.handle2(2);
21             Future<String> a9 = returnSuccTaskHandler.handle3(2);
22             while (true){
23                 // 如果任務都做完就執行如下邏輯
24                 if (a1.isDone() &&
25                         a2.isDone()&&
26                         a3.isDone()&&
27                         a4.isDone()&&
28                         a5.isDone()&&
29                         a6.isDone()&&
30                         a7.isDone()&&
31                         a8.isDone()&&
32                         a9.isDone()){
33                     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
34                     System.out.println(format.format(new Date()) + "async task end.");
35                     System.out.println("async result:"+a1.get());
36                     System.out.println("async result:"+a2.get());
37                     System.out.println("async result:"+a3.get());
38                     System.out.println("async result:"+a3.get());
39                     System.out.println("async result:"+a4.get());
40                     System.out.println("async result:"+a5.get());
41                     System.out.println("async result:"+a6.get());
42                     System.out.println("async result:"+a7.get());
43                     System.out.println("async result:"+a8.get());
44                     System.out.println("async result:"+a9.get());
45                     break;
46                 }
47             }
48         } catch (InterruptedException | ExecutionException e) {
49             e.printStackTrace();
50         }
51     }
52 
53 
54 }

 

輸出結果如下,我們可以發現 ,1、可以拿到返回結果,2、在最後一個子任務執行完成後,即立刻拿到結果。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章