线程池应用场景:
服务中嵌入邮件通知/异常通过消息系统报警等
尽量减少影响原服务效率的不重要服务,需要采用线程池异步方式调用
步骤:
1、启动类配置线程池启用注解
@EnableAsyn
2、可选:配置配置类(不配的话就是默认的)
package com.a;
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;
@Configuration
@EnableAsync
public class ExecutorConfig {
private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCapacity = 100;
public static final String EXECUTORE_COMMON = "commonExecutor";
public static final String EXECUTOR_MAIL = "mailExecutor";
@Bean
public Executor mailExecutor() { return configExecutor(EXECUTOR_MAIL); }
@Bean
public Executor commonExecutor() {
return configExecutor("commonExecutor");
}
private Executor configExecutor(String threadNamePrefix) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix(threadNamePrefix);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
3、在需要开启异步的方法上使用**@Async**注解,方法不能为privated
如果使用配置类的配置,则加上对应配置的bean名称,
比如@Async(“mailExecutor”)
4、注意日志编写
比如线程池的开启与结束,邮件发送内容,邮件发送结果等加上日志