说明
在程序执行过程中,我们经常需要开一个线程去处理其他的事情,并且是异步的,但是在高并发的情况下,如果不断的直接去new Thread的话线程很快会被耗光,然后程序就卡死了,我们需要一个异步的线程池去管理和调度这些线程。在Spring中有一个ThreadPoolTaskExecutor类为我们封装了方法,只需要少量配置即可使用
快速开始
由于是Spring的类,所以pom没啥特殊的就一个Springboot项目该有的就不写了。
编写启动类,注意使用@EnableAsync
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@SpringBootApplication
// 异步线程开启
@EnableAsync
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
@Bean
public AsyncTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("my-sync");
//配置核心线程数
executor.setCorePoolSize(5);
//配置最大线程数
executor.setMaxPoolSize(6);
//配置队列大小
executor.setQueueCapacity(99999);
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
编写一个工具类(其中有异步方法,我这里是发邮件),注意使用@Async
@Component
public class AsyncMailUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncMailUtil.class);
@Autowired
private JavaMailSender mailSender;
@Async("asyncTaskExecutor")
public void test1(SomeDTO someDTO) {
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setFrom("[email protected]");//设置发信人
message.setTo(someDTO.getEmail()); // 设置收信人
message.setSubject("申请驳回"); // 设置主题
message.setText("测试1");
// 发送邮件
mailSender.send(mimeMessage);
} catch (Exception e) {
LOGGER.error("发送邮件异常,原因:", e);
}
}
@Async("asyncTaskExecutor")
public void test2(SomeDTO someDTO) {
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setFrom("[email protected]");//设置发信人
message.setTo(someDTO.getEmail()); // 设置收信人
message.setSubject("主题"); // 设置主题
message.setText("测试2");
// 发送邮件
mailSender.send(mimeMessage);
} catch (Exception e) {
LOGGER.error("发送邮件异常,原因:", e);
}
}
}
使用:
@Autowired
private AsyncMailUtil mailUtil;
public void test(){
// 设置信息
someDTO.setxxx();
// 异步邮件
mailUtil.test1(someDTO);
mailUtil.test2(someDTO);
}