異步線程池在SpringBoot下的使用

說明

在程序執行過程中,我們經常需要開一個線程去處理其他的事情,並且是異步的,但是在高併發的情況下,如果不斷的直接去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);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章