最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

開啟異步支持

首先,需要在Spring Boot應(yīng)用中開啟異步支持。這可以通過在一個配置類上添加@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;
    }
}

定義異步服務(wù)

然后,定義一個服務(wù)類,并在其中的方法上使用@Async注解來標(biāo)記它們?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() {
        // 模擬異步任務(wù)
        try {
            Thread.sleep(1000);
            return CompletableFuture.completedFuture("單個任務(wù)執(zhí)行完成");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return CompletableFuture.failedFuture(e);
        }
    }

    @Async
    public CompletableFuture<String> processAsyncParallel(int taskNumber) {
        // 模擬異步任務(wù)
        try {
            Thread.sleep(1000); // 假設(shè)這是耗時操作
            return CompletableFuture.completedFuture("任務(wù) #" + 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í)行方法并等待所有任務(wù)完成

AsyncController中,我們將添加一個映射來啟動并行任務(wù)并等待它們?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();

        // 等待所有任務(wù)完成
        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 "并行任務(wù)開始執(zhí)行";
    }

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

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

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

說明

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

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

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

相關(guān)文章

  • JVM的垃圾處理機制詳解

    JVM的垃圾處理機制詳解

    JVM通過可達(dá)性分析確定垃圾對象,采用分代收集策略:新生代用復(fù)制算法(Eden+Survivor),老年代用標(biāo)記-整理,現(xiàn)代收集器如G1兼顧吞吐與延遲,ZGC/Shenandoah實現(xiàn)超低延遲,適用于不同場景
    2025-09-09
  • java中的arrays.sort()代碼詳解

    java中的arrays.sort()代碼詳解

    這篇文章主要介紹了Java中的Arrays.sort()代碼詳解,涉及Arrays.sort()簡單示例,策略模式,”super”的使用等相關(guān)內(nèi)容,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • spring mvc+localResizeIMG實現(xiàn)HTML5端圖片壓縮上傳

    spring mvc+localResizeIMG實現(xiàn)HTML5端圖片壓縮上傳

    這篇文章主要為大家詳細(xì)介紹了使用spring mvc+localResizeIMG實現(xiàn)HTML5端圖片壓縮上傳,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • Spring Boot MyBatis 連接數(shù)據(jù)庫配置示例

    Spring Boot MyBatis 連接數(shù)據(jù)庫配置示例

    本篇文章主要介紹了Spring Boot MyBatis 連接數(shù)據(jù)庫示例的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-02-02
  • Spring Security和自定義filter的沖突導(dǎo)致多執(zhí)行的解決方案

    Spring Security和自定義filter的沖突導(dǎo)致多執(zhí)行的解決方案

    這篇文章主要介紹了Spring Security和自定義filter的沖突導(dǎo)致多執(zhí)行的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • MybatisX無法自動生成entity實體類的解決方法

    MybatisX無法自動生成entity實體類的解決方法

    本文主要介紹了MybatisX無法自動生成entity實體類的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • Java中Thread類的使用和它的屬性

    Java中Thread類的使用和它的屬性

    在java中可以進(jìn)行多線程編程,在java標(biāo)準(zhǔn)庫中提供了一個Thread類,來表示線程操作,本文主要介紹了Java中Thread類的使用和它的屬性,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • Java中方法的重載與重寫舉例比較

    Java中方法的重載與重寫舉例比較

    這篇文章主要給大家介紹了關(guān)于Java中方法的重載與重寫的相關(guān)資料,Java中的方法重載和重寫是面向?qū)ο缶幊讨械膬蓚€重要概念,文中介紹的非常詳細(xì),需要的朋友可以參考下
    2023-07-07
  • MyBatis XML方式的基本用法之多表查詢功能的示例代碼

    MyBatis XML方式的基本用法之多表查詢功能的示例代碼

    這篇文章主要介紹了MyBatis XML方式的基本用法之多表查詢功能的示例代碼,本文通過示例文字相結(jié)合的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-07-07
  • 教你如何精準(zhǔn)統(tǒng)計出你的接口

    教你如何精準(zhǔn)統(tǒng)計出你的接口"QPS"

    今天小編就為大家分享一篇關(guān)于QPS的精準(zhǔn)計算方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2021-08-08

最新評論

齐河县| 施甸县| 泸西县| 全南县| 常州市| 万宁市| 利津县| 阿拉尔市| 宁河县| 惠水县| 平罗县| 永定县| 洛南县| 花莲县| 综艺| 杭锦后旗| 始兴县| 焦作市| 平度市| 安达市| 饶河县| 江城| 碌曲县| 根河市| 米脂县| 同心县| 孝感市| 南靖县| 陇西县| 凌云县| 黄龙县| 阜宁县| 栾城县| 乐业县| 综艺| 奉新县| 平定县| 怀化市| 贺兰县| 徐州市| 百色市|