1.xml中声明Bean
<!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->
<!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->
<!-- DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程) -->
<!-- DiscardPolicy:抛弃当前任务,但是不抛出异常;会导致被丢弃的任务无法再次被执行 -->
<bean id="mailrejectedExecutionHandler" class="java.util.concurrent.ThreadPoolExecutor$AbortPolicy"/>
<!-- 发送邮件线程池 -->
<bean id="mailThreadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" destroy-method="destroy">
<property name="corePoolSize" value="${email.threadPool.corePoolSize|8}"/>
<property name="maxPoolSize" value="${email.threadPool.maxPoolSize|10}"/>
<property name="queueCapacity" value="${email.threadPool.queueCapacity|10000}"/>
<property name="rejectedExecutionHandler" ref="mailrejectedExecutionHandler"/>
<property name="allowCoreThreadTimeOut" value="${email.threadPool.allowCoreThreadTimeOut|true}"/>
<property name="keepAliveSeconds" value="${email.threadPool.keepAliveSeconds|30}"/>
</bean>
2.properties文件中声明线程池的核心连接数 最大连接数 最大队列长度 等参数
email.threadPool.corePoolSize=8
email.threadPool.maxPoolSize=10
email.threadPool.queueCapacity=10000
email.threadPool.allowCoreThreadTimeOut=true
email.threadPool.keepAliveSeconds=30
3.java代码中注入MailThreadPool
@Lazy
@Service("emailService")
public class EmailServiceImpl implements EmailService {
@Autowired
private ThreadPoolTaskExecutor mailThreadPool;
public void doTradePdfSendCustEmail(Map<String,Object> map){
try {
mailThreadPool.execute(() -> {
try {
LOGGER.info("{}线程执行发送邮件方法,邮件模板内容map={}", Thread.currentThread().getName(), map);
TimeUnit.MILLISECONDS.sleep(10000);
//TODO 发送逻辑
} catch (InterruptedException | ParseException e) {
LOGGER.info("发送通知给客户={}失败:{}", e, e.getMessage());
}
});
}catch (Exception e){
LOGGER.info("发送通知给客户={}失败:{}", e, e.getMessage());
}
}
}
版权声明:本文为BearDie原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。