欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解SpringBoot中異步請求的實現(xiàn)與并行執(zhí)行

 更新時間:2024年02月06日 08:07:33   作者:一只愛擼貓的程序猿  
這篇文章主要為大家詳細介紹了在SpringBoot中如何是實現(xiàn)異步請求、并行執(zhí)行,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下

在Spring Boot中實現(xiàn)異步請求、并行執(zhí)行,可以使用@Async注解來定義異步方法,同時使用Future、CompletableFuture或其他異步處理機制來處理異步結(jié)果和回調(diào)。以下是實現(xiàn)這一功能的幾個步驟:

開啟異步支持

首先,需要在Spring Boot應用中開啟異步支持。這可以通過在一個配置類上添加@EnableAsync注解來實現(xiàn)。AsyncConfig 類開啟異步支持并自定義Executor

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("Async-");
        executor.initialize();
        return executor;
    }
}

定義異步服務

然后,定義一個服務類,并在其中的方法上使用@Async注解來標記它們?yōu)楫惒椒椒ā_@里可以返回Future、CompletableFutureListenableFuture等,以便處理異步結(jié)果。

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class AsyncService {

    @Async
    public CompletableFuture<String> processAsync() {
        // 模擬異步任務
        try {
            Thread.sleep(1000);
            return CompletableFuture.completedFuture("單個任務執(zhí)行完成");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return CompletableFuture.failedFuture(e);
        }
    }

    @Async
    public CompletableFuture<String> processAsyncParallel(int taskNumber) {
        // 模擬異步任務
        try {
            Thread.sleep(1000); // 假設這是耗時操作
            return CompletableFuture.completedFuture("任務 #" + taskNumber + " 執(zhí)行完成");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return CompletableFuture.failedFuture(e);
        }
    }

    public List<CompletableFuture<String>> executeTasksInParallel() {
        List<CompletableFuture<String>> futures = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            futures.add(processAsyncParallel(i));
        }
        return futures;
    }
}

在Controller中調(diào)用并行執(zhí)行方法并等待所有任務完成

AsyncController中,我們將添加一個映射來啟動并行任務并等待它們?nèi)客瓿伞?/p>

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/startParallelTasks")
    public String startParallelTasks() {
        List<CompletableFuture<String>> futures = asyncService.executeTasksInParallel();

        // 等待所有任務完成
        CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .thenApply(v -> futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList()));

        allDoneFuture.thenAccept(results -> results.forEach(System.out::println));

        return "并行任務開始執(zhí)行";
    }

    @GetMapping("/waitForSpecificTask")
    public String waitForSpecificTask() throws Exception {
        CompletableFuture<String> future = asyncService.processAsync();

        // 等待特定任務完成
        String result = future.get(); // 阻塞直到任務完成

        return "特定任務完成,結(jié)果:" + result;
    }
}

說明

  • executeTasksInParallel方法在AsyncService中啟動了多個并行的異步任務。這些任務通過CompletableFuture并行執(zhí)行。
  • startParallelTasks中,我們使用CompletableFuture.allOf來等待所有任務完成。allOf返回一個新的CompletableFuture,該CompletableFuture在所有給定的CompletableFutures完成時完成。
  • waitForSpecificTask方法演示了如何等待一個特定的異步任務完成。使用CompletableFuture.get()方法可以阻塞當前線程直到異步任務完成,并獲取結(jié)果。

代碼示例展示了如何在Spring Boot應用中并行執(zhí)行多個異步任務,并等待特定或所有任務的完成,充分利用@Async注解和CompletableFuture的能力來實現(xiàn)高效的異步編程模式。

到此這篇關(guān)于詳解SpringBoot中異步請求的實現(xiàn)與并行執(zhí)行的文章就介紹到這了,更多相關(guān)SpringBoot異步請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot2.0整合tk.mybatis異常解決

    SpringBoot2.0整合tk.mybatis異常解決

    本文主要介紹了SpringBoot2.0整合tk.mybatis異常,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-12-12
  • SpringBoot項目報錯:"Error?starting?ApplicationContext...."解決辦法

    SpringBoot項目報錯:"Error?starting?ApplicationContext....

    這篇文章主要給大家介紹了關(guān)于SpringBoot項目報錯:“Error?starting?ApplicationContext.?To?display?the?conditions?report?re-run?...”的解決辦法,文中通過圖文介紹的非常詳細,需要的朋友可以參考下
    2022-08-08
  • Java漢字轉(zhuǎn)拼音工具類完整代碼實例

    Java漢字轉(zhuǎn)拼音工具類完整代碼實例

    這篇文章主要介紹了java漢字轉(zhuǎn)拼音工具類完整代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-03-03
  • Java實現(xiàn)inputstream流的復制代碼實例

    Java實現(xiàn)inputstream流的復制代碼實例

    這篇文章主要介紹了Java實現(xiàn)inputstream流的復制代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • SpringBoot實現(xiàn)RBAC權(quán)限校驗模型的示例

    SpringBoot實現(xiàn)RBAC權(quán)限校驗模型的示例

    本文主要介紹了SpringBoot實現(xiàn)RBAC權(quán)限校驗模型的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2025-04-04
  • Java?死鎖解決方案順序鎖和輪詢鎖

    Java?死鎖解決方案順序鎖和輪詢鎖

    這篇文章主要介紹了Java?死鎖解決方案順序鎖和輪詢鎖,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-05-05
  • 將SpringBoot項目無縫部署到Tomcat服務器的操作流程

    將SpringBoot項目無縫部署到Tomcat服務器的操作流程

    SpringBoot 是一個用來簡化 Spring 應用初始搭建以及開發(fā)過程的框架,我們可以通過內(nèi)置的 Tomcat 容器來輕松地運行我們的應用,本文給大家介紹 SpringBoot 項目部署到獨立 Tomcat 服務器的操作流程,需要的朋友可以參考下
    2024-05-05
  • Java加載與存儲指令之ldc與_fast_aldc指令

    Java加載與存儲指令之ldc與_fast_aldc指令

    ldc指令將int、float、或者一個類、方法類型或方法句柄的符號引用、還可能是String型常量值從常量池中推送至棧頂。這一篇介紹一個虛擬機規(guī)范中定義的一個字節(jié)碼指令ldc,另外還有一個虛擬機內(nèi)部使用的字節(jié)碼指令_fast_aldc。需要的盆友可參考下面文章的內(nèi)容
    2021-09-09
  • Collections工具類_動力節(jié)點Java學院整理

    Collections工具類_動力節(jié)點Java學院整理

    Collections工具類提供了大量針對Collection/Map的操作。這篇文章主要介紹了Collections工具類_動力節(jié)點Java學院整理,需要的朋友可以參考下
    2017-04-04
  • Linux中Elasticsearch的安裝詳細步驟

    Linux中Elasticsearch的安裝詳細步驟

    這篇文章主要介紹了Linux中Elasticsearch的安裝詳細步驟,Elasticsearch(ES)是一種分布式、可擴展的搜索和分析引擎,基于Lucene構(gòu)建,它支持實時數(shù)據(jù)處理、全文搜索、實時分析等多種功能,需要的朋友可以參考下
    2024-12-12

最新評論