解決SpringBoot中使用@Async注解失效的問題
錯誤示例,同一個類中使用異步方法:
package com.xqnode.learning.controller;import com.fasterxml.jackson.core.JsonProcessingException;import org.springframework.scheduling.annotation.Async;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;import java.util.concurrent.TimeUnit;@RestController@RequestMapping('/test')public class TestController { @GetMapping('/async') public Map<Object, Object> test() throws InterruptedException, JsonProcessingException { System.out.println('接收到請求。。。'); task(); Map<Object, Object> map = new HashMap<>(); System.out.println('請求結束。。。'); map.put('msg', '操作成功'); map.put('code', '0'); return map; } @Async void task() throws InterruptedException { TimeUnit.SECONDS.sleep(5); System.out.println('線程任務執行結束。。。'); }}
來分析下錯誤的原因:
當我使用postman調用該接口的時候發現,我預想中的立即返回并沒有發生。后來查詢資料發現,在controller調用本類中的異步方法,不會生效
正確示例:
package com.xqnode.learning.controller;import com.xqnode.learning.service.AsyncService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;@RestController@RequestMapping('/test')public class TestController { private static final Logger LOG = LoggerFactory.getLogger(TestController.class); @Autowired private AsyncService asyncService; @GetMapping('/async') public Map<Object, Object> test() throws InterruptedException { LOG.info('接收到請求。。。'); asyncService.task(); Map<Object, Object> map = new HashMap<>(); LOG.info('請求結束。。。'); map.put('msg', '操作成功'); map.put('code', '0'); return map; }}
將異步調用放到service中:
package com.xqnode.learning.service;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;@Servicepublic class AsyncService { private static final Logger LOG = LoggerFactory.getLogger(AsyncService.class); @Async('asyncExecutor') public void task() throws InterruptedException { TimeUnit.SECONDS.sleep(5); LOG.info('線程任務執行結束。。。'); }}
這時候再重啟項目請求該接口,就會發現接口可以立即返回值。而task任務是異步執行的,5秒之后才會打印結果:
補充知識:springboot + @Async 實現異步方法之踩坑填坑
在使用@Async注解實現異步方法的時候,我們項目中實現了AsyncConfigurer接口來自定義線程池和異常處理。其中自定義線程池的代碼如上圖,異常處理項目中是自定義異常類實現AsyncUncaughtExceptionHandler 接口,這里未貼出代碼。那么到底踩了什么坑呢?
第一:
加了@Async注解的方法調不起來。由于我不是項目及代碼的原創,花了很多時間才分析出問題。經過仔細分析,由于業務場景需要,我們在項目啟動的時候就創建了3個線程(也就是創建了3個任務)這正好占滿了核心線程數(3個),當調到@Async的方法時,相當于有新的任務進來,結合線程池的原理可知,新的任務都會放到阻塞隊列里面去,直到阻塞隊列滿了才可能會創建新的線程來執行任務或者執行飽和策略(這與Runtime.getRuntime().availableProcessors()能獲取到的線程數有關),所以造成了異步方法調不起來的假象。
解決方法:根據實際情況將線程池的核心線程數和最大線程數調整到合適的值。
第二:
在解決了上一個問題后,又發現了新的問題,后面某段代碼看不到執行的日志,也不知道錯在哪里,沒有錯誤日志。由于之前項目的日志并不詳細,在逐步完善各處日志后,終于發現問題,報出了某個實體類沒有默認構造函數的錯誤。在@Async異步方法中有一個把json轉成實體bean的操作,由于這個bean創建了有參構造函數,卻沒有默認的無參構造函數,所以拋異常了,正好被getAsyncUncaughtExceptionHandler()捕捉到,由于當時此方法沒有日志,也是花了點時間的。
解決方法:完善日志,給實體類加上無參構造函數。
通過這兩個問題,自己也總結了一下,在使用線程池相關的知識時,一定要先了解原理,不然可能給自己挖坑,還有就是平常寫代碼時要養成寫注釋和打日志的習慣,否則出問題時可能要多花很久的時間找問題。
以上這篇解決SpringBoot中使用@Async注解失效的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: