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

Springboot使用異步方法優(yōu)化Service邏輯,提高接口響應(yīng)速度方式

 更新時間:2025年06月25日 08:37:51   作者:yololee_  
這篇文章主要介紹了Springboot使用異步方法優(yōu)化Service邏輯,提高接口響應(yīng)速度方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

使用異步方法優(yōu)化Service邏輯,提高接口響應(yīng)速度

一、業(yè)務(wù)場景

例如生成驗證碼和發(fā)送驗證碼組成的業(yè)務(wù),其實無需等到真正發(fā)送成功驗證碼才對客戶端進行響應(yīng),可以讓短信發(fā)送者一個耗時操作轉(zhuǎn)為異步執(zhí)行

二、異步任務(wù)在springboot的使用

@RestController
public class AsyncArticleController {
    @Autowired
    private ArticleService articleService;

    /**
     * 模擬獲取文章后閱讀量+1
     */
    @PostMapping("/article")
    public String getArticle() {
        // 查詢文章
        String article = articleService.selectArticle();
        // 閱讀量+1
        articleService.updateReadCount();
        System.out.println("getArticle文章閱讀業(yè)務(wù)執(zhí)行完畢");
        return article;
    }
}
@Service
public class ArticleService {
    // 查詢文章
    public String selectArticle() {
        // TODO 模擬文章查詢操作
        System.out.println("查詢?nèi)蝿?wù)線程,線程名:"+Thread.currentThread().getName());
        return "文章詳情";
    }

    // 文章閱讀量+1
    @Async
    public void updateReadCount() {
        // TODO 模擬耗時操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新任務(wù)線程,線程名:"+Thread.currentThread().getName());
    }
}
@SpringBootApplication
@EnableAsync
public class SpringbootRunnerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRunnerApplication.class, args);
    }

}

在這里插入圖片描述

注意:

@EnableAsync // 使用異步方法時需要提前開啟(在啟動類上或配置類上)
@Async // 被async注解修飾的方法由SpringBoot默認(rèn)線程池(SimpleAsyncTaskExecutor)執(zhí)行

三、自定義線程池執(zhí)行異步方法

第一步配置自定義線程池

package com.hl.springbootrunner.asyncdemo.config;

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

@EnableAsync // 開啟多線程, 項目啟動時自動創(chuàng)建
@Configuration
public class AsyncConfig {
    @Bean("readCountExecutor") //指定自定義線程池名稱
    public ThreadPoolTaskExecutor asyncOperationExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 設(shè)置核心線程數(shù)
        executor.setCorePoolSize(8);
        // 設(shè)置最大線程數(shù)
        executor.setMaxPoolSize(20);
        // 設(shè)置隊列大小
        executor.setQueueCapacity(Integer.MAX_VALUE);
        // 設(shè)置線程活躍時間(秒)
        executor.setKeepAliveSeconds(60);
        // 設(shè)置線程名前綴+分組名稱
        executor.setThreadNamePrefix("AsyncOperationThread-");
        executor.setThreadGroupName("AsyncOperationGroup");
        // 所有任務(wù)結(jié)束后關(guān)閉線程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 初始化
        executor.initialize();
        return executor;
    }
}

第二步, 在@Async注解上指定執(zhí)行的線程池,ArticleService中指定執(zhí)行的線程池

 // 文章閱讀量+1,指定線程池
    @Async("readCountExecutor")
    public void updateReadCountByExecutor() {
        // TODO 模擬耗時操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新任務(wù)線程,線程名:"+Thread.currentThread().getName());
    }

第三步,在AsyncArcicleController中

/**
     * 模擬獲取文章后閱讀量+1,指定線程池
     */
    @PostMapping("/articleByExecutor")
    public String getArticleByExecutor() {
        // 查詢文章
        String article = articleService.selectArticle();
        // 閱讀量+1
        articleService.updateReadCountByExecutor();
        System.out.println("getArticleByExecutor文章閱讀業(yè)務(wù)執(zhí)行完畢");
        return article;
    }

在這里插入圖片描述

四、捕獲(無返回值的)異步方法中的異常

自定義異常處理類CustomAsyncExceptionHandler

@Component
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
        System.out.println("異常捕獲---------------------------------");
        System.out.println("Exception message - " + throwable.getMessage());
        System.out.println("Method name - " + method.getName());
        for (Object param : obj) {
            System.out.println("Parameter value - " + param);
        }
        System.out.println("異常捕獲---------------------------------");
    }
}
@Async("readCountExecutor")
    public void updateReadCountNoReturnByExecutor() {
        // TODO 模擬耗時操作
        try {
            Thread.sleep(3000);
            int i = 1/0;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新任務(wù)線程,線程名:"+Thread.currentThread().getName());
    }

在這里插入圖片描述

五、捕獲(有返回值)異步方法中的異常

使用Future類及其子類來接收異步方法返回值

// 文章閱讀量+1
    @Async("readCountExecutor")
    public CompletableFuture<Integer> updateReadCountHasResult() {
        // TODO 模擬耗時操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新文章閱讀量線程"+Thread.currentThread().getName());
        return CompletableFuture.completedFuture(100 + 1);
    }
@GetMapping("/articleCompletableFuture")
    public String getArticleCompletableFuture() throws ExecutionException, InterruptedException {
        // 查詢文章
        String article = articleService.selectArticle();
        // 閱讀量+1
        CompletableFuture<Integer> future = articleService.updateReadCountHasResult();
        //無返回值的異步方法拋出異常不會影響Controller的主要業(yè)務(wù)邏輯
        //有返回值的異步方法拋出異常會影響Controller的主要業(yè)務(wù)邏輯
        int count = 0;
        // 循環(huán)等待異步請求結(jié)果
        while (true) {
            if(future.isCancelled()) {
                System.out.println("異步任務(wù)取消");
                break;
            }
            if (future.isDone()) {
                count = future.get();
                System.out.println(count);
                break;
            }
        }
        System.out.println("getArticleCompletableFuture文章閱讀業(yè)務(wù)執(zhí)行完畢");
        return article + count;
    }

在這里插入圖片描述

注意:

  • 無返回值的異步方法拋出異常不會影響Controller的主要業(yè)務(wù)邏輯
  • 有返回值的異步方法拋出異常會影響Controller的主要業(yè)務(wù)邏輯

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Springboot集成Camunda使用Mysql介紹

    Springboot集成Camunda使用Mysql介紹

    大家好,本篇文章主要講的是Springboot集成Camunda使用Mysql介紹,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • 攔截Druid數(shù)據(jù)源自動注入帳密解密實現(xiàn)詳解

    攔截Druid數(shù)據(jù)源自動注入帳密解密實現(xiàn)詳解

    這篇文章主要為大家介紹了攔截Druid數(shù)據(jù)源自動注入帳密解密實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • 6種SpringBoot解決跨域請求的方法整理

    6種SpringBoot解決跨域請求的方法整理

    跨域資源共享是一種標(biāo)準(zhǔn)機制,允許服務(wù)器聲明哪些源可以訪問其資源,在SpringBoot應(yīng)用中,有多種方式可以解決跨域問題,本文主要介紹了6種常見的解決方案,大家可以根據(jù)需求自行選擇
    2025-04-04
  • 解決swagger2中@ApiResponse的response不起作用

    解決swagger2中@ApiResponse的response不起作用

    這篇文章主要介紹了解決swagger2中@ApiResponse的response不起作用問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • SpringBoot+RabbitMQ+Redis實現(xiàn)商品秒殺的示例代碼

    SpringBoot+RabbitMQ+Redis實現(xiàn)商品秒殺的示例代碼

    本文主要介紹了SpringBoot+RabbitMQ+Redis實現(xiàn)商品秒殺,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • 使用Mybatis遇到的坑之Integer類型參數(shù)的解讀

    使用Mybatis遇到的坑之Integer類型參數(shù)的解讀

    這篇文章主要介紹了使用Mybatis遇到的坑之Integer類型參數(shù)的解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java異常繼承結(jié)構(gòu)解析_動力節(jié)點Java學(xué)院整理

    Java異常繼承結(jié)構(gòu)解析_動力節(jié)點Java學(xué)院整理

    這篇文章主要介紹了Java異常繼承結(jié)構(gòu)解析的相關(guān)知識,需要的朋友可以參考下
    2017-04-04
  • java實現(xiàn)讀取jar包中配置文件的幾種方式

    java實現(xiàn)讀取jar包中配置文件的幾種方式

    本文主要介紹了java實現(xiàn)讀取jar包中配置文件的幾種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • java中Instant類使用詳解(附完整實例)

    java中Instant類使用詳解(附完整實例)

    Java中的Instant是一個不可變的類,用于表示時間的單個點,精確到納秒級別,這篇文章主要介紹了java中Instant類使用的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-07-07
  • Java算法題常用函數(shù)詳解

    Java算法題常用函數(shù)詳解

    這篇文章主要介紹了Java中常用的字符串操作、字符串轉(zhuǎn)換、字符串處理、字符串緩沖區(qū)、棧、數(shù)組、列表、隊列、優(yōu)先隊列、Map和HashMap的常用函數(shù)和操作,感興趣的朋友跟隨小編一起看看吧
    2025-11-11

最新評論

霸州市| 茶陵县| 贵州省| 清水县| 依兰县| 来宾市| 临颍县| 桐乡市| 温宿县| 垫江县| 将乐县| 顺昌县| 宁国市| 正定县| 綦江县| 普兰店市| 东台市| 龙南县| 库车县| 仁布县| 丹阳市| 红安县| 镇康县| 克拉玛依市| 施秉县| 承德县| 彰武县| 新野县| 开封市| 咸丰县| 南乐县| 枞阳县| 长垣县| 林周县| 饶平县| 清河县| 房产| 甘谷县| 建宁县| 磐石市| 吉木萨尔县|