天天看點

springboot怎樣使用多線程異步發送郵件

一、引入郵件發送依賴

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
           

二、配置檔案

#QQ郵箱伺服器
spring.mail.host=smtp.qq.com
#端口号
spring.mail.port=587
#你的QQ郵箱賬戶
spring.mail.username=你的QQ号@qq.com
#你的QQ郵箱第三方授權碼
spring.mail.password=你的QQ郵箱第三方授權碼
#編碼類型
spring.mail.default-encoding=UTF-8

           

三、自定義@Async線程池

package com.trade.market.Thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync//開啟異步功能
public class BaseAsyncConfigurer implements AsyncConfigurer {

    private static final Logger LOG = LoggerFactory.getLogger(BaseAsyncConfigurer.class);
    /**
     * 核心線程數10:線程池建立時候初始化的線程數
     * 最大線程數20:線程池最大的線程數,隻有在緩沖隊列滿了之後才會申請超過核心線程數的線程
     * 緩沖隊列200:用來緩沖執行任務的隊列
     * 允許線程的空閑時間60秒:當超過了核心線程出之外的線程在空閑時間到達之後會被銷毀
     * 線程池名的字首:設定好了之後可以友善我們定位處理任務所在的線程池
     * 線程池對拒絕任務的處理政策:這裡采用了CallerRunsPolicy政策,當線程池沒有處理能力的時候,該政策會直接在 execute 方法的調用線程中運作被拒絕的任務;如果執行程式已關閉,則會丢棄該任務
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();//初始化
        return executor;
    }

    /*異步任務中異常處理*/
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (Throwable ex, Method method, Object... params)->{
            //todo 異步方法異常處理
            LOG.error("class#method: {}" ,method.getDeclaringClass().getName() ,"#{}" ,method.getName());
            LOG.error("type        : {}" , ex.getClass().getName());
            LOG.error("exception   : {}" , ex.getMessage());
        };
    }

}

           

四、定義郵件發送工具類

package com.trade.market.Thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SendEmail{
    @Resource
    private JavaMailSenderImpl mailSenderl;
    @Value("${spring.mail.username}")
    private String from;

    private static final Logger LOG = LoggerFactory.getLogger(SendEmail.class);

    @Async
    public void sendSimpleEmail(String to,String subject,String text){
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
//        發送郵件
        mailSenderl.send(message);
        LOG.info("郵件發送結果:發送成功!");
    }
}

           

五、使用方法

springboot怎樣使用多線程異步發送郵件
springboot怎樣使用多線程異步發送郵件