spring框架如何调用异步方法?快进来学学吧
生活随笔
收集整理的這篇文章主要介紹了
spring框架如何调用异步方法?快进来学学吧
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
定義一個配置類
這里一個默認的線程池,一個起了自己名字的線程池。(可以配置多個線程池)
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);//最大線程數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();// 設置核心線程數executor.setCorePoolSize(5);// 設置最大線程數executor.setMaxPoolSize(10);// 設置隊列容量executor.setQueueCapacity(20);// 設置線程活躍時間(秒)executor.setKeepAliveSeconds(60);// 設置默認線程名稱executor.setThreadNamePrefix("test-");// 設置拒絕策略executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 等待所有任務結束后再關閉線程池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
總結
以上是生活随笔為你收集整理的spring框架如何调用异步方法?快进来学学吧的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 只是简单读了读《oracle查询优化改写
- 下一篇: 如何用redis实现分布式锁?这篇文章教