springboot配置ThreadPoolTaskExecutor线程池

概念:创建线程要花费昂贵的资源和时间,如果任务来了才创建线程那么响应时间会变长,而且一个进程能创建的线程数有限。为了避免这些问题,在程序启动的时候就创建若干线程来响应处理,它们被称为线程池。

1启动类添加注解开启线程异步

@SpringBootApplication
@EnableAsync//开启Springboot对于异步任务的支持
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

2添加线程配置类

@Configuration
@EnableAsync
public class AsyncTaskConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPool.setCorePoolSize(10);
        //设置最大线程数
        threadPool.setMaxPoolSize(100);
        //线程池所使用的缓冲队列
        threadPool.setQueueCapacity(10);
        //等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(60);
        //  线程名称前缀
        threadPool.setThreadNamePrefix("Derry-Async-");
        // 初始化线程
        threadPool.initialize();
        return threadPool;
    }

    /**
     * 异步异常处理
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

3多线程实现业务

@Service
public class AsyncTaskService {

    public static final Logger logger = LoggerFactory.getLogger(AsyncTaskService.class);

     @Autowired
    private JavaMailSender sender;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @Async
    public void sendEmailAsync(User user, CountDownLatch latch) {
        MailReceiver(user);
        latch.countDown();
    }

    public void MailReceiver(User user) {
        //收到消息,发送邮件
        MimeMessage msg = sender.createMimeMessage();
        try {
            // true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(msg);
            helper.setFrom(from);
            helper.setTo(user.getTo());
            helper.setSubject(user.getSubject());
            helper.setText(user.getText(), true);
            sender.send(msg);
            logger.info("html邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送html邮件时发生异常!", e);
        }
    }
}

@Async无效

异步方法(sendEmailAsync)和调用方法(调用sendEmailAsync)一定要 写在不同的类中 ,如果写在一个类中,是没有效果的

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring中,可以使用ThreadPoolTaskExecutor来创建线程池并执行异步任务。当线程池中的线程抛出异常,可以通过设置异常处理器来处理这些异常。 以下是一个示例代码,演示了如何配置ThreadPoolTaskExecutor并处理异常: ```java import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; public class MyTaskExecutor { private ThreadPoolTaskExecutor threadPoolTaskExecutor; public MyTaskExecutor() { threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(5); threadPoolTaskExecutor.setMaxPoolSize(50); threadPoolTaskExecutor.setQueueCapacity(100); threadPoolTaskExecutor.setKeepAliveSeconds(30000); threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); threadPoolTaskExecutor.setThreadNamePrefix("MyTaskExecutor-"); threadPoolTaskExecutor.initialize(); } public void executeTask(Runnable task) { threadPoolTaskExecutor.execute(task); } public void shutdown() { threadPoolTaskExecutor.shutdown(); } public int getActiveCount() { return threadPoolTaskExecutor.getActiveCount(); } } ``` 在上面的代码中,我们创建了一个名为MyTaskExecutor的类,它使用ThreadPoolTaskExecutor来执行任务。我们设置了核心线程数、最大线程数、缓冲任务队列的长度和线程的存活间。我们还设置了拒绝策略为CallerRunsPolicy,这意味着当线程池无法接受新任务,会使用调用线程来执行任务。 你可以根据自己的需求来配置ThreadPoolTaskExecutor,并在executeTask方法中执行你的任务。如果任务抛出异常,你可以在任务的代码中进行异常处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值