spring boot使用@Async非同步註解,原理+原始碼

_否極泰來發表於2021-06-20

1、java的大部分介面的方法都是序列執行的,但是有些業務場景是不需要同步返回結果的,可以把結果直接返回,具體業務非同步執行,也有些業務介面是需要並行獲取資料,最後把資料聚合在統一返回給前端。
通常我們都是採用多執行緒的方式來實現上述業務功能,但spring 提供更優雅的方式來實現上述功能,就是@Async 非同步註解,在方法上新增@Async,spring就會藉助AOP,非同步執行方法。

1、如何啟用@Async

spring boot通過@EnableAsync 註解啟用@Async非同步註解
實現AsyncConfigurer介面,getAsyncExecutor是預設自定義的執行緒池

/**
 * 執行緒池配置(@Async)
 */
@Slf4j
@EnableAsync
@Configuration
public class SimpleExecutorConfig implements AsyncConfigurer {
    /** 執行緒池維護執行緒的最少數量 */
    @Value("${executor.corePoolSize}")
    private Integer corePoolSize;

    /** 執行緒池維護執行緒的最大數量 */
    @Value("${executor.maxPoolSize}")
    private Integer maxPoolSize;

    /** 緩衝佇列的大小 */
    @Value("${executor.queueCapacity}")
    private Integer queueCapacity;

    /** 為每個執行緒名設定一個字首(1) */
    @Value("${executor.threadNamePrefix}")
    private String threadNamePrefix;

    /** 為每個執行緒名設定一個字首(2) */
    @Value("${executor.threadNamePrefix_2}")
    private String threadNamePrefix_2;


    @Bean(ExecutorConstant.simpleExecutor_1)
    @Override
    public Executor getAsyncExecutor() {
        //執行緒池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setThreadNamePrefix(threadNamePrefix);
        taskExecutor.initialize();
        return taskExecutor;
    }


    @Bean(ExecutorConstant.simpleExecutor_2)
    public Executor asyncExecutor2() {
        //執行緒池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setThreadNamePrefix(threadNamePrefix_2);
        taskExecutor.initialize();
        return taskExecutor;
    }
}

2、如何使用@Async

下面是程式碼:
TestAsyncService類:

@Slf4j
@Service
public class TestAsyncService implements ITestAsyncService {

    /**
     * 非同步方法,無返回值
     * @return
     */
    @Async
    @Override
    public void asyncFunction_1(){
        handleBusinessTime();
        log.info("asyncFunction_1 當前執行緒名稱是:{}",Thread.currentThread().getName());
    };

    /////////////////非同步方法,無返回值(指定執行緒池) start
    /**
     * 非同步方法,無返回值(指定執行緒池)
     * @return
     */
    @Async(value = ExecutorConstant.simpleExecutor_2)
    @Override
    public void asyncFunction_2(){
        handleBusinessTime();
        log.info("asyncFunction_2 當前執行緒名稱是:{}",Thread.currentThread().getName());
    };

    @Async(ExecutorConstant.simpleExecutor_2)
    @Override
    public void asyncFunction_3(){
        handleBusinessTime();
        log.info("asyncFunction_3 當前執行緒名稱是:{}",Thread.currentThread().getName());

    };
    /////////////////非同步方法,無返回值(指定執行緒池) end

    /**
     * 非同步方法,有返回值
     * @return
     */
    @Async
    @Override
    public Future<Integer> asyncReturnDta_1(){
        handleBusinessTime();
        log.info("asyncReturnDta_1 當前執行緒名稱是:{}",Thread.currentThread().getName());
        return new AsyncResult<Integer>(1);
    };
    /**
     * 非同步方法,有返回值(指定執行緒池)
     * @return
     */
    @Async(ExecutorConstant.simpleExecutor_2)
    @Override
    public Future<Integer> asyncReturnDta_2(){
        handleBusinessTime();
        log.info("asyncReturnDta_2 當前執行緒名稱是:{}",Thread.currentThread().getName());
        return new AsyncResult<Integer>(1);
    };


    /**
     * 非同步方法,有返回值-超時
     * @return
     */
    @Async
    @Override
    public Future<Integer> asyncReturnDtaTimeOut(){
        handleBusinessTime();
        handleBusinessTime();
        handleBusinessTime();
        handleBusinessTime();
        log.info("asyncReturnDta_3 當前執行緒名稱是:{}",Thread.currentThread().getName());
        return new AsyncResult<Integer>(1);
    };

    /**
     * 這方法 模擬處理業務或者 去運算元據庫 消耗的時間
     */
    public static void handleBusinessTime(){
        //去資料庫查詢資料耗時 start
        int[] sleepTime = NumberUtil.generateRandomNumber(2000,5000,1);
        try {
            //Thread.sleep 休眠的時候 相當於 業務操作,或者請求資料庫的需要消耗的時間
            Thread.sleep(sleepTime[0]);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //去資料庫查詢資料耗時 end
    }
}

TestAsyncController

@Slf4j
@RestController
@RequestMapping(value = "/v1/async")
public class TestAsyncController {

    @Autowired
    ITestAsyncService testAsyncService;

    @ApiOperation(value = "呼叫介面")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Resp<Integer> test() throws ExecutionException, InterruptedException {
        log.info("asyncFunction_1 start");
        testAsyncService.asyncFunction_1();
        log.info("asyncFunction_1 start");

        log.info("asyncFunction_2 start");
        testAsyncService.asyncFunction_2();
        log.info("asyncFunction_2 end");

        log.info("asyncFunction_3 start");
        testAsyncService.asyncFunction_3();
        log.info("asyncFunction_3 end");


        log.info("asyncReturnDta_1 & asyncReturnDta_2 start");
        Future<Integer> future = testAsyncService.asyncReturnDta_1();
        testAsyncService.asyncReturnDta_2();
        log.info("asyncReturnDta_1 & asyncReturnDta_2 end");

        Integer resp = future.get();
        log.info("future.get() resp:{}",resp);
        return Resp.buildDataSuccess(resp);
    }

    @ApiOperation(value = "呼叫介面-超時")
    @RequestMapping(value = "/async_timeOut", method = RequestMethod.GET)
    public Resp<Integer> async_timeOut() throws ExecutionException, InterruptedException {
        TimeInterval timeInterval = DateUtil.timer();
        log.info("asyncReturnDtaTimeOut start");
        Future<Integer> future = testAsyncService.asyncReturnDtaTimeOut();
        log.info("asyncReturnDtaTimeOut end");

        Integer resp = null;
        try {
            //一秒內 返回不了資料就報錯
            resp = future.get(1, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            resp = -1;//請求超時了,相當於熔斷,服務降級
            log.error("asyncReturnDtaTimeOut future.get(1, TimeUnit.SECONDS) timeout:",e);
        }

        log.info("future.get() resp:{}  耗時:{}毫秒",resp,timeInterval.intervalRestart());
        return Resp.buildDataSuccess(resp);
    }

}



/v1/async/test 介面:

2021-06-20 21:09:30.490  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : asyncFunction_1 start
2021-06-20 21:09:30.490  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : asyncFunction_1 start
2021-06-20 21:09:30.490  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : asyncFunction_2 start
2021-06-20 21:09:30.491  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : asyncFunction_2 end
2021-06-20 21:09:30.491  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : asyncFunction_3 start
2021-06-20 21:09:30.491  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : asyncFunction_3 end
2021-06-20 21:09:30.491  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : asyncReturnDta_1 & asyncReturnDta_2 start
2021-06-20 21:09:30.492  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : asyncReturnDta_1 & asyncReturnDta_2 end
2021-06-20 21:09:32.679  INFO 14207 --- [le-1-executor-9] c.e.multi.service.impl.TestAsyncService  : asyncFunction_1 當前執行緒名稱是:my-simple-1-executor-9
2021-06-20 21:09:33.454  INFO 14207 --- [le-2-executor-8] c.e.multi.service.impl.TestAsyncService  : asyncFunction_3 當前執行緒名稱是:my-simple-2-executor-8
2021-06-20 21:09:33.578  INFO 14207 --- [le-2-executor-9] c.e.multi.service.impl.TestAsyncService  : asyncReturnDta_2 當前執行緒名稱是:my-simple-2-executor-9
2021-06-20 21:09:34.101  INFO 14207 --- [e-1-executor-10] c.e.multi.service.impl.TestAsyncService  : asyncReturnDta_1 當前執行緒名稱是:my-simple-1-executor-10
2021-06-20 21:09:34.102  INFO 14207 --- [nio-8666-exec-7] c.e.m.controller.TestAsyncController     : future.get() resp:1
2021-06-20 21:09:34.357  INFO 14207 --- [le-2-executor-7] c.e.multi.service.impl.TestAsyncService  : asyncFunction_2 當前執行緒名稱是:my-simple-2-executor-7

從日誌上可以看出,都是非同步執行的


/v1/async/async_timeOut 介面:

2021-06-20 21:20:58.886  INFO 14427 --- [nio-8666-exec-1] c.e.m.controller.TestAsyncController     : asyncReturnDtaTimeOut start
2021-06-20 21:20:58.890  INFO 14427 --- [nio-8666-exec-1] c.e.m.controller.TestAsyncController     : asyncReturnDtaTimeOut end
2021-06-20 21:20:59.899 ERROR 14427 --- [nio-8666-exec-1] c.e.m.controller.TestAsyncController     : asyncReturnDtaTimeOut future.get(1, TimeUnit.SECONDS) timeout:

java.util.concurrent.TimeoutException: null
	at java.util.concurrent.FutureTask.get(FutureTask.java:205) ~[na:1.8.0_231]
	at com.example.multi.controller.TestAsyncController.async_timeOut(TestAsyncController.java:69) ~[classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_231]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_231]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_231]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_231]
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) [spring-web-5.3.8.jar:5.3.8]
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) [spring-web-5.3.8.jar:5.3.8]
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) [spring-webmvc-5.3.8.jar:5.3.8]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) [spring-webmvc-5.3.8.jar:5.3.8]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) [spring-webmvc-5.3.8.jar:5.3.8]
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) [spring-webmvc-5.3.8.jar:5.3.8]
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) [spring-webmvc-5.3.8.jar:5.3.8]
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) [spring-webmvc-5.3.8.jar:5.3.8]
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.3.8.jar:5.3.8]
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) [spring-webmvc-5.3.8.jar:5.3.8]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:626) [tomcat-embed-core-9.0.46.jar:4.0.FR]
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.3.8.jar:5.3.8]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) [tomcat-embed-core-9.0.46.jar:4.0.FR]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) [spring-web-5.3.8.jar:5.3.8]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) [spring-web-5.3.8.jar:5.3.8]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) [spring-web-5.3.8.jar:5.3.8]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.3.8.jar:5.3.8]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_231]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_231]
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.46.jar:9.0.46]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_231]

2021-06-20 21:20:59.900  INFO 14427 --- [nio-8666-exec-1] c.e.m.controller.TestAsyncController     : future.get() resp:-1  耗時:1014毫秒
2021-06-20 21:21:12.105  INFO 14427 --- [le-1-executor-1] c.e.multi.service.impl.TestAsyncService  : asyncReturnDta_3 當前執行緒名稱是:my-simple-1-executor-1

從日誌上看出,如果future.get(1, TimeUnit.SECONDS) 到了超時時間,直接丟擲超時異常,走主執行緒後續程式碼。
比較適合 規定時間範圍內要返回資料(超時可以根據業務場景,返回一個預設值,或者返回值值就是空的)的業務場景

@Async原理+原始碼

原理:是通過spring aop + 執行緒池的方式來實現的
原始碼:
原始碼的方法位置是:AsyncExecutionInterceptor.invoke
image

  1. 107行:是獲取一個執行緒池
  2. 108行:如果沒有設定執行緒池丟擲異常
  3. 113行:是建立一個執行緒物件 他的run方法執行invocation.proceed()【走實際業務程式碼】
  4. 121和124行:走的是統一的異常處理 主要是呼叫handleUncaughtException方法,SimpleExecutorConfig 實現了AsyncConfigurer介面它就有getAsyncUncaughtExceptionHandler方法,可以重寫這個方法,實現自定義的異常處理

下圖是AsyncConfigurer介面可以實現的方法:

image

doSubmit方法:

實際上就是呼叫執行緒池的submit方法:
image

具體程式碼,我上傳到gitee,大家感興趣可以clone 傳送門~

@Async原始碼參考於:
https://www.cnblogs.com/dennyzhangdd/p/9026303.html

相關文章