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

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

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

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

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

例如生成驗(yàn)證碼和發(fā)送驗(yàn)證碼組成的業(yè)務(wù),其實(shí)無(wú)需等到真正發(fā)送成功驗(yàn)證碼才對(duì)客戶端進(jìn)行響應(yīng),可以讓短信發(fā)送者一個(gè)耗時(shí)操作轉(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 模擬耗時(shí)操作
        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 // 使用異步方法時(shí)需要提前開啟(在啟動(dòng)類上或配置類上)
@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 // 開啟多線程, 項(xiàng)目啟動(dòng)時(shí)自動(dòng)創(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è)置隊(duì)列大小
        executor.setQueueCapacity(Integer.MAX_VALUE);
        // 設(shè)置線程活躍時(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 模擬耗時(shí)操作
        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;
    }

在這里插入圖片描述

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

自定義異常處理類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 模擬耗時(shí)操作
        try {
            Thread.sleep(3000);
            int i = 1/0;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("更新任務(wù)線程,線程名:"+Thread.currentThread().getName());
    }

在這里插入圖片描述

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

使用Future類及其子類來(lái)接收異步方法返回值

// 文章閱讀量+1
    @Async("readCountExecutor")
    public CompletableFuture<Integer> updateReadCountHasResult() {
        // TODO 模擬耗時(shí)操作
        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();
        //無(wú)返回值的異步方法拋出異常不會(huì)影響Controller的主要業(yè)務(wù)邏輯
        //有返回值的異步方法拋出異常會(huì)影響Controller的主要業(yè)務(wù)邏輯
        int count = 0;
        // 循環(huán)等待異步請(qǐng)求結(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;
    }

在這里插入圖片描述

注意:

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

總結(jié)

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

相關(guān)文章

  • Springboot集成Camunda使用Mysql介紹

    Springboot集成Camunda使用Mysql介紹

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

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

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

    6種SpringBoot解決跨域請(qǐng)求的方法整理

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

最新評(píng)論

通榆县| 定安县| 金华市| 大石桥市| 涿州市| 区。| 遂昌县| 安顺市| 济阳县| 永寿县| 泰州市| 仙桃市| 仁怀市| 青神县| 米林县| 科技| 池州市| 新田县| 阿坝县| 阿合奇县| 承德市| 青冈县| 汨罗市| 汝城县| 马山县| 襄城县| 五原县| 乌海市| 沛县| 宕昌县| 卓尼县| 普宁市| 景泰县| 安多县| 德庆县| 珲春市| 边坝县| 清流县| 通渭县| 桃江县| 鹿泉市|