spring-boot 自定义Executor的配置方法及@Async的使用

简单几步,实现异步新线程调用。


1、在主类中添加@EnableAsync注解:

[java]  view plain  copy
  1. @SpringBootApplication  
  2. @EnableScheduling  
  3. @EnableAsync  
  4. public class MySpringBootApplication {  
  5.     private static Logger logger = LoggerFactory.getLogger(MySpringBootApplication.class);  
  6.       
  7.     public static void main(String[] args) {  
  8.         SpringApplication.run(MySpringBootApplication.class, args);  
  9.         logger.info("My Spring Boot Application Started");  
  10.     }  
  11.   
  12.       
  13. }  

2、创建一个AsyncTask类,在里面添加两个用@Async注解的task:

[java]  view plain  copy
  1. /** 
  2.  * Asynchronous Tasks 
  3.  * @author Xu 
  4.  * 
  5.  */  
  6. @Component  
  7. public class AsyncTask {  
  8.     protected final Logger logger = LoggerFactory.getLogger(this.getClass());  
  9.       
  10.     @Async  
  11.     public Future<String> doTask1() throws InterruptedException{  
  12.         logger.info("Task1 started.");  
  13.         long start = System.currentTimeMillis();  
  14.         Thread.sleep(5000);  
  15.         long end = System.currentTimeMillis();  
  16.           
  17.         logger.info("Task1 finished, time elapsed: {} ms.", end-start);  
  18.           
  19.         return new AsyncResult<>("Task1 accomplished!");  
  20.     }  
  21.       
  22.     @Async  
  23.     public Future<String> doTask2() throws InterruptedException{  
  24.         logger.info("Task2 started.");  
  25.         long start = System.currentTimeMillis();  
  26.         Thread.sleep(3000);  
  27.         long end = System.currentTimeMillis();  
  28.           
  29.         logger.info("Task2 finished, time elapsed: {} ms.", end-start);  
  30.           
  31.         return new AsyncResult<>("Task2 accomplished!");  
  32.     }  
  33. }  
3、万事俱备,开始测试:

[java]  view plain  copy
  1. public class TaskTests extends BasicUtClass{  
  2.     @Autowired  
  3.     private AsyncTask asyncTask;  
  4.       
  5.       
  6.     @Test  
  7.     public void AsyncTaskTest() throws InterruptedException, ExecutionException {  
  8.         Future<String> task1 = asyncTask.doTask1();  
  9.         Future<String> task2 = asyncTask.doTask2();  
  10.           
  11.         while(true) {  
  12.             if(task1.isDone() && task2.isDone()) {  
  13.                 logger.info("Task1 result: {}", task1.get());  
  14.                 logger.info("Task2 result: {}", task2.get());  
  15.                 break;  
  16.             }  
  17.             Thread.sleep(1000);  
  18.         }  
  19.           
  20.         logger.info("All tasks finished.");  
  21.     }  
  22. }  

测试结果:

[plain]  view plain  copy
  1. 2016-12-13 11:12:24,850:INFO main (AsyncExecutionAspectSupport.java:245) - No TaskExecutor bean found for async processing  
  2. 2016-12-13 11:12:24,864:INFO SimpleAsyncTaskExecutor-1 (AsyncTask.java:22) - Task1 started.  
  3. 2016-12-13 11:12:24,865:INFO SimpleAsyncTaskExecutor-2 (AsyncTask.java:34) - Task2 started.  
  4. 2016-12-13 11:12:27,869:INFO SimpleAsyncTaskExecutor-2 (AsyncTask.java:39) - Task2 finished, time elapsed: 3001 ms.  
  5. 2016-12-13 11:12:29,866:INFO SimpleAsyncTaskExecutor-1 (AsyncTask.java:27) - Task1 finished, time elapsed: 5001 ms.  
  6. 2016-12-13 11:12:30,853:INFO main (TaskTests.java:23) - Task1 result: Task1 accomplished!  
  7. 2016-12-13 11:12:30,853:INFO main (TaskTests.java:24) - Task2 result: Task2 accomplished!  
  8. 2016-12-13 11:12:30,854:INFO main (TaskTests.java:30) - All tasks finished.  

可以看到,没有自定义的Executor,所以使用缺省的TaskExecutor 。


前面是最简单的使用方法。如果想使用自定义的Executor,可以按照如下几步来:

1、新建一个Executor配置类,顺便把@EnableAsync注解搬到这里来:

[java]  view plain  copy
  1. @Configuration  
  2. @EnableAsync  
  3. public class ExecutorConfig {  
  4.   
  5.     /** Set the ThreadPoolExecutor's core pool size. */  
  6.     private int corePoolSize = 10;  
  7.     /** Set the ThreadPoolExecutor's maximum pool size. */  
  8.     private int maxPoolSize = 200;  
  9.     /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */  
  10.     private int queueCapacity = 10;  
  11.   
  12.     @Bean  
  13.     public Executor mySimpleAsync() {  
  14.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  
  15.         executor.setCorePoolSize(corePoolSize);  
  16.         executor.setMaxPoolSize(maxPoolSize);  
  17.         executor.setQueueCapacity(queueCapacity);  
  18.         executor.setThreadNamePrefix("MySimpleExecutor-");  
  19.         executor.initialize();  
  20.         return executor;  
  21.     }  
  22.       
  23.     @Bean  
  24.     public Executor myAsync() {  
  25.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  
  26.         executor.setCorePoolSize(corePoolSize);  
  27.         executor.setMaxPoolSize(maxPoolSize);  
  28.         executor.setQueueCapacity(queueCapacity);  
  29.         executor.setThreadNamePrefix("MyExecutor-");  
  30.   
  31.         // rejection-policy:当pool已经达到max size的时候,如何处理新任务  
  32.         // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行  
  33.         executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());  
  34.         executor.initialize();  
  35.         return executor;  
  36.     }  
  37. }  

这里定义了两个不同的Executor,第二个重新设置了pool已经达到max size时候的处理方法;同时指定了线程名字的前缀。

2、自定义Executor的使用:

[java]  view plain  copy
  1. /** 
  2.  * Asynchronous Tasks 
  3.  * @author Xu 
  4.  * 
  5.  */  
  6. @Component  
  7. public class AsyncTask {  
  8.     protected final Logger logger = LoggerFactory.getLogger(this.getClass());  
  9.       
  10.     @Async("mySimpleAsync")  
  11.     public Future<String> doTask1() throws InterruptedException{  
  12.         logger.info("Task1 started.");  
  13.         long start = System.currentTimeMillis();  
  14.         Thread.sleep(5000);  
  15.         long end = System.currentTimeMillis();  
  16.           
  17.         logger.info("Task1 finished, time elapsed: {} ms.", end-start);  
  18.           
  19.         return new AsyncResult<>("Task1 accomplished!");  
  20.     }  
  21.       
  22.     @Async("myAsync")  
  23.     public Future<String> doTask2() throws InterruptedException{  
  24.         logger.info("Task2 started.");  
  25.         long start = System.currentTimeMillis();  
  26.         Thread.sleep(3000);  
  27.         long end = System.currentTimeMillis();  
  28.           
  29.         logger.info("Task2 finished, time elapsed: {} ms.", end-start);  
  30.           
  31.         return new AsyncResult<>("Task2 accomplished!");  
  32.     }  
  33. }  
就是把上面自定义Executor的类名,放进@Async注解中。


3、测试(测试用例不变)结果:

[plain]  view plain  copy
  1. 2016-12-13 10:57:11,998:INFO MySimpleExecutor-1 (AsyncTask.java:22) - Task1 started.  
  2. 2016-12-13 10:57:12,001:INFO MyExecutor-1 (AsyncTask.java:34) - Task2 started.  
  3. 2016-12-13 10:57:15,007:INFO MyExecutor-1 (AsyncTask.java:39) - Task2 finished, time elapsed: 3000 ms.  
  4. 2016-12-13 10:57:16,999:INFO MySimpleExecutor-1 (AsyncTask.java:27) - Task1 finished, time elapsed: 5001 ms.  
  5. 2016-12-13 10:57:17,994:INFO main (TaskTests.java:23) - Task1 result: Task1 accomplished!  
  6. 2016-12-13 10:57:17,994:INFO main (TaskTests.java:24) - Task2 result: Task2 accomplished!  
  7. 2016-12-13 10:57:17,994:INFO main (TaskTests.java:30) - All tasks finished.  
  8. 2016-12-13 10:57:18,064 Thread-3 WARN Unable to register Log4j shutdown hook because JVM is shutting down. Using SimpleLogger  

可见,线程名字的前缀变了,两个task使用了不同的线程池了。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值