异步线程池在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("xxx@qq.com");//设置发信人
            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("xxx@qq.com");//设置发信人
            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);
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值