更多內(nèi)容請瀏覽本人博客
java發(fā)送郵件的方法網(wǎng)上有很多,但是大多是屬于阻塞式發(fā)送,spring 提供了很方便的實(shí)現(xiàn)多線程方法,結(jié)合spring可以快速實(shí)現(xiàn)異步發(fā)送郵件.
- 引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 此外還需引入springboot 核心包-->
- 配置spring連接池
創(chuàng)建配置類,實(shí)現(xiàn)AsyncConfigurer
@Configuration
public class AsyncTaskConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
// 線程池維護(hù)線程的最少數(shù)量
taskExecutor.setCorePoolSize(10);
// 線程池維護(hù)線程的最大數(shù)量
taskExecutor.setMaxPoolSize(50);
// 緩存隊(duì)列
taskExecutor.setQueueCapacity(99999);
// 對拒絕task的處理策略
//(1) 默認(rèn)的ThreadPoolExecutor.AbortPolicy 處理程序遭到拒絕將拋出運(yùn)行時(shí)RejectedExecutionException;
//(2) ThreadPoolExecutor.CallerRunsPolicy 線程調(diào)用運(yùn)行該任務(wù)的 execute 本身蔑舞。此策略提供簡單的反饋控制機(jī)制渗柿,能夠減緩新任務(wù)的提交速度
//(3) ThreadPoolExecutor.DiscardPolicy 不能執(zhí)行的任務(wù)將被刪除;
//(4) ThreadPoolExecutor.DiscardOldestPolicy 如果執(zhí)行程序尚未關(guān)閉,則位于工作隊(duì)列頭部的任務(wù)將被刪除辰如,然后重試執(zhí)行程序(如果再次失敗赞咙,則重復(fù)此過程)
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 線程名前綴,方便排查問題
taskExecutor.setThreadNamePrefix("order-send-thread-");
// 注意一定要初始化
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
- 創(chuàng)建發(fā)送郵件工具類
此工具類出于本人的需要編寫,可根據(jù)實(shí)際需求改寫
public class EmailUtils {
// 引入javaMailSender
private JavaMailSender mailSender;
public EmailUtils(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
// 發(fā)送簡單郵件
public void sendSimpleMail(String from, String to, String cc, String subject, String text) {
if(StringUtils.isBlank(to)){
return;
}
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to.split(","));
if (StringUtils.isNotBlank(cc)) {
message.setCc(cc.split(","));
}
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
// 發(fā)送帶多個(gè)附件的郵件
public void sendAttachmentMail(String from, String to, String cc, String subject, String text, List<Attachment> attachments) throws Exception {
if(StringUtils.isBlank(to)){
return;
}
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(to.split(","));
if (StringUtils.isNotBlank(cc)) {
helper.setCc(cc.split(","));
}
helper.setSubject(subject);
helper.setText(text);
for (Attachment attachment : attachments) {
String attachmentName = attachment.attachmentName;
DataSource attachmentFile = attachment.attachmentFile;
helper.addAttachment(attachmentName, attachmentFile);
}
mailSender.send(mimeMessage);
}
// 發(fā)送帶單個(gè)附件的郵件
public void sendAttachmentMail(String from, String to, String cc, String subject, String text, Attachment attachment) throws Exception {
if (StringUtils.isBlank(to)) {
return;
}
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(to.split(","));
if (StringUtils.isNotBlank(cc)) {
helper.setCc(cc.split(","));
}
helper.setSubject(subject);
helper.setText(text);
String attachmentName = attachment.attachmentName;
DataSource attachmentFile = attachment.attachmentFile;
helper.addAttachment(attachmentName, attachmentFile);
mailSender.send(mimeMessage);
}
public static class Attachment {
private String attachmentName;
private DataSource attachmentFile;
public Attachment(String attachmentName, DataSource attachmentFile) {
this.attachmentName = attachmentName;
this.attachmentFile = attachmentFile;
}
}
}
- 創(chuàng)建發(fā)送郵件service
@Service
@Slf4j
@EnableAspectJAutoProxy(exposeProxy = true)
public class OrderSendService {
@Autowired
private JavaMailSender mailSender;
@Async//注意此注解,有坑
public void asyncSendEmail(String from, String to, String cc, String subject, String text, List<OrderExcelEntity> orderList) throws Exception {
EmailUtils emailUtils = new EmailUtils(mailSender);
DataSource excelDataSource = generateExcelDataSource(orderList);
EmailUtils.Attachment attachment = new EmailUtils.Attachment("XXX.xls", excelDataSource);
emailUtils.sendAttachmentMail(from, to, cc, subject, text, attachment);
}
}
springboot 實(shí)現(xiàn)發(fā)送郵件的核心方法已完成,引用時(shí)最好根據(jù)本人實(shí)際需要進(jìn)行改寫.
需要注意的是,當(dāng)本類中非異步方法調(diào)用asyncSendEmail()時(shí),怎么也不能實(shí)現(xiàn)異步,比方說我需要定時(shí)調(diào)用此異步發(fā)送郵件方法
@Scheduled(cron = "0 1 0/1 * * ? ")
public void sendMailTimer() {
((OrderSendService) AopContext.currentProxy()).asyncSendEmail(from, to, cc,subject,text,orderList);
}
填坑方法:
1.在類上增加 @EnableAspectJAutoProxy(exposeProxy = true) 注解
2.調(diào)用時(shí)增加 ((OrderSendService) AopContext.currentProxy())
自此springboot 實(shí)現(xiàn)異步發(fā)送郵件方法已完成,有不對之處,歡迎指正