詳解Spring Boot 異步執(zhí)行方法
最近遇到一個需求,就是當(dāng)服務(wù)器接到請求并不需要任務(wù)執(zhí)行完成才返回結(jié)果,可以立即返回結(jié)果,讓任務(wù)異步的去執(zhí)行。開始考慮是直接啟一個新的線程去執(zhí)行任務(wù)或者把任務(wù)提交到一個線程池去執(zhí)行,這兩種方法都是可以的。但是 Spring 這么強大,肯定有什么更簡單的方法,就 google 了一下,還真有呢。就是使用 @EnableAsync 和 @Async 這兩個注解就 ok 了。
給方法加上 @Async 注解
package me.deweixu.aysncdemo.service; public interface AsyncService { void asyncMethod(String arg); }
package me.deweixu.aysncdemo.service.ipml; import me.deweixu.aysncdemo.service.AsyncService; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncServiceImpl implements AsyncService { @Async @Override public void asyncMethod(String arg) { System.out.println("arg:" + arg); System.out.println("=====" + Thread.currentThread().getName() + "========="); } }
@EnableAsync
在啟動類或者配置類加上 @EnableAsync 注解
package me.deweixu.aysncdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @SpringBootApplication public class AysncDemoApplication { public static void main(String[] args) { SpringApplication.run(AysncDemoApplication.class, args); } }
測試
package me.deweixu.aysncdemo; import me.deweixu.aysncdemo.service.AsyncService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class AysncDemoApplicationTests { @Autowired AsyncService asyncService; @Test public void testAsync() { System.out.println("=====" + Thread.currentThread().getName() + "========="); asyncService.asyncMethod("Async"); } }
=====main=========
2018-03-25 21:30:31.391 INFO 28742 --- [ main] .s.a.AnnotationAsyncExecutionInterceptor : No task executor bean found for async processing: no bean of type TaskExecutor and no bean named 'taskExecutor' either
arg:Async
=====SimpleAsyncTaskExecutor-1=========
從上面的結(jié)果看 asyncService.asyncMethod("Async") 確實異步執(zhí)行了,它使用了一個新的線程。
指定 Executor
從上面執(zhí)行的日志可以猜測到 Spring 默認(rèn)使用 SimpleAsyncTaskExecutor 來異步執(zhí)行任務(wù)的,可以搜索到這個類。@Async 也可以指定自定義的 Executor。
在啟動類中增加自定義的 Executor
package me.deweixu.aysncdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; @EnableAsync @SpringBootApplication public class AysncDemoApplication { public static void main(String[] args) { SpringApplication.run(AysncDemoApplication.class, args); } @Bean(name = "threadPoolTaskExecutor") public Executor threadPoolTaskExecutor() { return new ThreadPoolTaskExecutor(); } }
指定 Executor
package me.deweixu.aysncdemo.service.ipml; import me.deweixu.aysncdemo.service.AsyncService; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class AsyncServiceImpl implements AsyncService { @Async("threadPoolTaskExecutor") @Override public void asyncMethod(String arg) { System.out.println("arg:" + arg); System.out.println("=====" + Thread.currentThread().getName() + "========="); } }
這樣在異步執(zhí)行任務(wù)的時候就使用 threadPoolTaskExecutor
設(shè)置默認(rèn)的 Executor
上面提到如果 @Async 不指定 Executor 就默認(rèn)使用 SimpleAsyncTaskExecutor,其實默認(rèn)的 Executor 是可以使用 AsyncConfigurer 接口來配置的
@Configuration public class SpringAsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { return new ThreadPoolTaskExecutor(); } }
異常捕獲
在異步執(zhí)行的方法中是可能出現(xiàn)異常的,我們可以在任務(wù)內(nèi)部使用 try catch 來處理異常,當(dāng)任務(wù)拋出異常時,Spring 也提供了捕獲它的方法。
實現(xiàn) AsyncUncaughtExceptionHandler 接口
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler { @Override public void handleUncaughtException( Throwable throwable, Method method, Object... obj) { System.out.println("Exception message - " + throwable.getMessage()); System.out.println("Method name - " + method.getName()); for (Object param : obj) { System.out.println("Parameter value - " + param); } } }
實現(xiàn) AsyncConfigurer 接口重寫 getAsyncUncaughtExceptionHandler 方法
@Configuration public class SpringAsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { return new ThreadPoolTaskExecutor(); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new CustomAsyncExceptionHandler(); } }
改寫 asyncMethod 方法使它拋出異常
@Async @Override public void asyncMethod(String arg) { System.out.println("arg:" + arg); System.out.println("=====" + Thread.currentThread().getName() + "========="); throw new NullPointerException(); }
運行結(jié)果:
=====main=========
arg:Async
=====threadPoolTaskExecutor-1=========
Exception message - Async NullPointerException
Method name - asyncMethod
Parameter value - Async
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
idea創(chuàng)建springboot項目和springcloud項目的詳細(xì)教程
這篇文章主要介紹了idea創(chuàng)建springboot項目和springcloud項目方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10微服務(wù)Spring?Boot?整合Redis?阻塞隊列實現(xiàn)異步秒殺下單思路詳解
這篇文章主要介紹了微服務(wù)Spring?Boot?整合Redis?阻塞隊列實現(xiàn)異步秒殺下單,使用阻塞隊列實現(xiàn)秒殺的優(yōu)化,采用異步秒殺完成下單的優(yōu)化,本文給大家分享詳細(xì)步驟及實現(xiàn)思路,需要的朋友可以參考下2022-10-10詳解Java的Struts2框架的結(jié)構(gòu)及其數(shù)據(jù)轉(zhuǎn)移方式
這篇文章主要介紹了詳解Java的Struts2框架的結(jié)構(gòu)及其數(shù)據(jù)轉(zhuǎn)移方式,Struts框架是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下2016-01-01淺談java實現(xiàn)redis的發(fā)布訂閱(簡單易懂)
本篇文章主要介紹了淺談java實現(xiàn) redis的發(fā)布訂閱(簡單易懂),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03java枚舉enum,根據(jù)value值獲取key鍵的操作
這篇文章主要介紹了java枚舉enum,根據(jù)value值獲取key鍵的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02SpringBoot中Shiro緩存使用Redis、Ehcache的方法
這篇文章主要介紹了SpringBoot中Shiro緩存使用Redis、Ehcache的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09