springboot使用线程池(@EnableAsync和@Async)
- 2020-06-05 15:49:00
- 1147533288 原创
- 10601
场景:
post请求,传参后,触发10家医院数据下发,需要同时触发多个ktr执行到不同数据库。
解决办法:
1.增加线程池配置,并发5,最大15,队列100
package com.neusoft.app.etlTask; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; public class ExecutorConfig { /** Set the ThreadPoolExecutor's core pool size. */ private int corePoolSize = 5; /** Set the ThreadPoolExecutor's maximum pool size. */ private int maxPoolSize = 15; /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */ private int queueCapacity = 100; public Executor taskAsync() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("TaskExecutor-"); // rejection-policy:当pool已经达到max size的时候,如何处理新任务 // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
2.编写待执行的etl转换任务,加入注解@Async
public class EtlTools { public void trans(int i){ SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss"); try { Thread.sleep(10000); System.out.println("执行任务"+i+" "+Thread.currentThread().getName()+" "+format.format(new Date())); } catch (InterruptedException e) { e.printStackTrace(); } } }
3.controller中请求执行,观察后台kettle日志输出,是不是5个在并发,旧任务跑完,会有新任务在跑的。
private EtlTools etlTools; ("/test") public void test(){ for (int i = 0; i < 10; i++) { etlTools.trans(i); } //立即返回,此时后台任务并未结束,刚刚开始。 }
关于kettle输出日志,参考另一篇springboot增加kettle5完整日志输出
原文地址
文章分类
联系我
| 联系人: | meepo |
|---|---|
| 电话: | ***** |
| Email: | 1147533288@qq.com |
| QQ: | 1147533288 |