日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring框架如何调用异步方法?快进来学学吧

發(fā)布時間:2025/3/19 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring框架如何调用异步方法?快进来学学吧 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

?

定義一個配置類

這里一個默認的線程池,一個起了自己名字的線程池。(可以配置多個線程池)

import org.springframework.aop.interceptor.AsyncExecutionAspectSupport; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.ThreadPoolExecutor;/*** 線程池配置、啟用異步* */ @EnableAsync(proxyTargetClass = true) @Configuration public class AsycTaskExecutorConfig {@Bean(name = AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME)public TaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();//核心線程池大小executor.setCorePoolSize(10);//最大線程數(shù)executor.setMaxPoolSize(20);//隊列容量executor.setQueueCapacity(200);//活躍時間executor.setKeepAliveSeconds(60);//線程名字前綴executor.setThreadNamePrefix("taskExecutor-");executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());return executor;}@Bean(name = "testEx")public TaskExecutor testEx() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// 設置核心線程數(shù)executor.setCorePoolSize(5);// 設置最大線程數(shù)executor.setMaxPoolSize(10);// 設置隊列容量executor.setQueueCapacity(20);// 設置線程活躍時間(秒)executor.setKeepAliveSeconds(60);// 設置默認線程名稱executor.setThreadNamePrefix("test-");// 設置拒絕策略executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 等待所有任務結(jié)束后再關(guān)閉線程池executor.setWaitForTasksToCompleteOnShutdown(true);return executor;} }

使用一下看看吧

@RequestMapping("/testAnys")public void testAnys(){System.out.println("testAnys");testAnysMethod();System.out.println("1");try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("2");testAnysMethod2();System.out.println("3");try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}@Async//這個使用默認的線程池public void testAnysMethod(){try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("async");}@Async("testEx")//這個使用自己命名的線程池public void testAnysMethod2(){try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("testEx");}

運行

testAnys
async
1
2
testEx
3

總結(jié)

以上是生活随笔為你收集整理的spring框架如何调用异步方法?快进来学学吧的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。