淺談SpringBoot實現(xiàn)異步調用的幾種方式
一、使用 CompletableFuture 實現(xiàn)異步任務
CompletableFuture 是 Java 8 新增的一個異步編程工具,它可以方便地實現(xiàn)異步任務。使用 CompletableFuture 需要滿足以下條件:
異步任務的返回值類型必須是 CompletableFuture 類型;
在異步任務中使用 CompletableFuture.supplyAsync() 或 CompletableFuture.runAsync() 方法來創(chuàng)建異步任務;
在主線程中使用 CompletableFuture.get() 方法獲取異步任務的返回結果。
我們創(chuàng)建一個服務類,里面包含了異步方法和普通方法。
import org.springframework.stereotype.Service; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; /** * @author qinxun * @date 2023-06-07 * @Descripion: 異步服務類 */ @Service public class AsyncService { /** * 普通任務操作1 */ public String task1() throws InterruptedException { TimeUnit.SECONDS.sleep(3); return "任務執(zhí)行完成1"; } /** * 普通任務操作2 */ public String task2() throws InterruptedException { TimeUnit.SECONDS.sleep(2); return "任務執(zhí)行完成2"; } /** * 普通任務操作3 */ public String task3() throws InterruptedException { TimeUnit.SECONDS.sleep(3); return "任務執(zhí)行完成3"; } /** * 異步操作1 */ public CompletableFuture<String> asyncTask1() { return CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { throw new RuntimeException(e); } return "異步任務執(zhí)行完成1"; }); } /** * 異步操作2 */ public CompletableFuture<String> asyncTask2() { return CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e); } return "異步任務執(zhí)行完成2"; }); } /** * 異步操作3 */ public CompletableFuture<String> asyncTask3() { return CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { throw new RuntimeException(e); } return "異步任務執(zhí)行完成3"; }); } }
我們先測試普通方法的情況,看看最后耗時
import cn.hutool.core.date.StopWatch; import com.example.quartzdemo.service.AsyncService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; /** * @author qinxun * @date 2023-06-07 * @Descripion: 異步處理測試 */ @SpringBootTest public class AsyncTest { @Autowired private AsyncService asyncService; @Test void test1() throws InterruptedException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); // 異步操作 /* CompletableFuture<String> completableFuture1 = asyncService.asyncTask1(); CompletableFuture<String> completableFuture2 = asyncService.asyncTask2(); CompletableFuture<String> completableFuture3 = asyncService.asyncTask3(); System.out.println(completableFuture1.get()); System.out.println(completableFuture2.get()); System.out.println(completableFuture3.get());*/ // 同步操作 System.out.println(asyncService.task1()); System.out.println(asyncService.task2()); System.out.println(asyncService.task3()); stopWatch.stop(); System.out.println("耗時:" + stopWatch.getTotalTimeMillis()); } }
程序執(zhí)行的結果:
任務執(zhí)行完成1
任務執(zhí)行完成2
任務執(zhí)行完成3
耗時:8008
我們可以發(fā)現(xiàn),普通同步方法是按順序一個個操作的,各個方法不會同時處理。下面我們把這些操作換成異步的方法測試。
import cn.hutool.core.date.StopWatch; import com.example.quartzdemo.service.AsyncService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * @author qinxun * @date 2023-06-07 * @Descripion: 異步處理測試 */ @SpringBootTest public class AsyncTest { @Autowired private AsyncService asyncService; @Test void test1() throws InterruptedException, ExecutionException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); // 異步操作 CompletableFuture<String> completableFuture1 = asyncService.asyncTask1(); CompletableFuture<String> completableFuture2 = asyncService.asyncTask2(); CompletableFuture<String> completableFuture3 = asyncService.asyncTask3(); System.out.println(completableFuture1.get()); System.out.println(completableFuture2.get()); System.out.println(completableFuture3.get()); // 同步操作 /*System.out.println(asyncService.task1()); System.out.println(asyncService.task2()); System.out.println(asyncService.task3());*/ stopWatch.stop(); System.out.println("耗時:" + stopWatch.getTotalTimeMillis()); } }
程序執(zhí)行結果:
異步任務執(zhí)行完成1
異步任務執(zhí)行完成2
異步任務執(zhí)行完成3
耗時:3008
發(fā)現(xiàn)幾個方法是異步同時進行的,沒有先后的順序,大大提高了程序執(zhí)行效率。
二、基于注解 @Async實現(xiàn)異步任務
@Async 注解是 Spring 提供的一種輕量級異步方法實現(xiàn)方式,它可以標記在方法上,用來告訴 Spring 這個方法是一個異步方法,Spring 會將這個方法的執(zhí)行放在異步線程中進行。使用 @Async 注解需要滿足以下條件:
需要在 Spring Boot 主類上添加 @EnableAsync 注解啟用異步功能;
需要在異步方法上添加 @Async 注解。
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication // 主類上加上這個注解,開啟異步功能 @EnableAsync public class QuartzDemoApplication { public static void main(String[] args) { SpringApplication.run(QuartzDemoApplication.class, args); } }
修改測試的服務層
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * @author qinxun * @date 2023-06-07 * @Descripion: 異步服務類 */ @Service public class AsyncService { /** * 同步任務操作1 */ public String task1() throws InterruptedException { TimeUnit.SECONDS.sleep(3); return "任務執(zhí)行完成1"; } /** * 同步任務操作2 */ public String task2() throws InterruptedException { TimeUnit.SECONDS.sleep(2); return "任務執(zhí)行完成2"; } /** * 同步任務操作3 */ public String task3() throws InterruptedException { TimeUnit.SECONDS.sleep(3); return "任務執(zhí)行完成3"; } /** * 異步操作1 */ @Async public Future<String> asyncTask1() throws InterruptedException { long currentTimeMillis = System.currentTimeMillis(); TimeUnit.SECONDS.sleep(3); long currentTimeMillis1 = System.currentTimeMillis(); System.out.println("task1任務耗時:" + (currentTimeMillis1 - currentTimeMillis) + "ms"); return new AsyncResult<>("task1完成"); } /** * 異步操作2 */ @Async public Future<String> asyncTask2() throws InterruptedException { long currentTimeMillis = System.currentTimeMillis(); TimeUnit.SECONDS.sleep(2); long currentTimeMillis1 = System.currentTimeMillis(); System.out.println("task1任務耗時:" + (currentTimeMillis1 - currentTimeMillis) + "ms"); return new AsyncResult<>("task2完成"); } /** * 異步操作3 */ @Async public Future<String> asyncTask3() throws InterruptedException { long currentTimeMillis = System.currentTimeMillis(); TimeUnit.SECONDS.sleep(3); long currentTimeMillis1 = System.currentTimeMillis(); System.out.println("task1任務耗時:" + (currentTimeMillis1 - currentTimeMillis) + "ms"); return new AsyncResult<>("task3完成"); } }
創(chuàng)建一個測試類
import com.example.quartzdemo.service.AsyncService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * @author qinxun * @date 2023-06-07 * @Descripion: */ @RestController public class AsyncController { @Autowired private AsyncService asyncService; /** * 測試異步 */ @RequestMapping("/async") public String testAsync() throws InterruptedException, ExecutionException { long currentTimeMillis = System.currentTimeMillis(); Future<String> task1 = asyncService.asyncTask1(); Future<String> task2 = asyncService.asyncTask2(); Future<String> task3 = asyncService.asyncTask3(); while (true) { if (task1.isDone() && task2.isDone() && task3.isDone()) { // 三個任務都調用完成,退出循環(huán)等待 break; } } System.out.println(task1.get()); System.out.println(task2.get()); System.out.println(task3.get()); long currentTimeMillis1 = System.currentTimeMillis(); return "task任務總耗時:" + (currentTimeMillis1 - currentTimeMillis) + "ms"; } }
執(zhí)行測試方法
task1任務耗時:2006ms
task1任務耗時:3011ms
task1任務耗時:3011ms
task1完成
task2完成
task3完成
三、使用 TaskExecutor 實現(xiàn)異步任務
TaskExecutor 是 Spring 提供的一個接口,它定義了一個方法 execute(),用來執(zhí)行異步任務。使用 TaskExecutor 需要滿足以下條件:
需要在 Spring 配置文件中配置一個 TaskExecutor 實例;
在異步方法中調用 TaskExecutor 實例的 execute() 方法來執(zhí)行異步任務。
創(chuàng)建一個異步配置類
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; /** * @author qinxun * @date 2023-06-07 * @Descripion: 異步處理配置類 */ @Configuration public class AsyncConfig implements AsyncConfigurer { @Bean(name = "asyncExecutor") public TaskExecutor asyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(100); executor.setThreadNamePrefix("async-"); executor.initialize(); return executor; } @Override public Executor getAsyncExecutor() { return asyncExecutor(); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
修改下服務類,我們使用自定義的異步配置
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; /** * @author qinxun * @date 2023-06-07 * @Descripion: 異步服務類 */ @Service public class AsyncService { @Autowired @Qualifier("asyncExecutor") private TaskExecutor taskExecutor; /** * 同步任務操作1 */ public String task1() throws InterruptedException { TimeUnit.SECONDS.sleep(3); return "任務執(zhí)行完成1"; } /** * 同步任務操作2 */ public String task2() throws InterruptedException { TimeUnit.SECONDS.sleep(2); return "任務執(zhí)行完成2"; } /** * 同步任務操作3 */ public String task3() throws InterruptedException { TimeUnit.SECONDS.sleep(3); return "任務執(zhí)行完成3"; } /** * 異步操作1 */ @Async public void asyncTask1() { taskExecutor.execute(() -> { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { throw new RuntimeException(e); } }); System.out.println("異步任務執(zhí)行完成1"); } /** * 異步操作2 */ @Async public void asyncTask2() throws InterruptedException { taskExecutor.execute(() -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e); } }); System.out.println("異步任務執(zhí)行完成2"); } /** * 異步操作3 */ @Async public void asyncTask3() throws InterruptedException { taskExecutor.execute(() -> { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { throw new RuntimeException(e); } }); System.out.println("異步任務執(zhí)行完成3"); } }
測試類進行測試
/** * @author qinxun * @date 2023-06-07 * @Descripion: 異步處理測試 */ @SpringBootTest public class AsyncTest { @Autowired @Qualifier("asyncExecutor") private TaskExecutor taskExecutor; @Test void test1() { StopWatch stopWatch = new StopWatch(); stopWatch.start(); // 異步操作 /* asyncService.asyncTask1(); asyncService.asyncTask2(); asyncService.asyncTask3();*/ taskExecutor.execute(() -> System.out.println("異步任務")); // 同步操作 /*System.out.println(asyncService.task1()); System.out.println(asyncService.task2()); System.out.println(asyncService.task3());*/ stopWatch.stop(); System.out.println("耗時:" + stopWatch.getTotalTimeMillis()); } }
耗時:6
異步任務執(zhí)行完成3
異步任務執(zhí)行完成1
異步任務執(zhí)行完成2
到此這篇關于淺談SpringBoot實現(xiàn)異步調用的幾種方式的文章就介紹到這了,更多相關SpringBoot 異步調用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java基于雙向環(huán)形鏈表解決丟手帕問題的方法示例
這篇文章主要介紹了java基于雙向環(huán)形鏈表解決丟手帕問題的方法,簡單描述了丟手帕問題,并結合實例形式給出了Java基于雙向環(huán)形鏈表解決丟手帕問題的步驟與相關操作技巧,需要的朋友可以參考下2017-11-11Java實現(xiàn)十秒向MySQL插入百萬條數(shù)據(jù)
這篇文章主要為大家詳細介紹了Java如何實現(xiàn)十秒向MySQL插入百萬條數(shù)據(jù),文中的示例代碼講解詳細,對我們學習或工作有一定借鑒價值,需要的可以參考一下2022-11-11Spring MVC全局異常處理和單元測試_動力節(jié)點Java學院整理
本篇文章主要介紹了Spring MVC全局異常處理和單元測試,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08java.util.Collections類—emptyList()方法的使用
這篇文章主要介紹了java.util.Collections類—emptyList()方法的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11