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)一定要 写在不同的类中 ,如果写在一个类中,是没有效果的

发布了34 篇原创文章 · 获赞 1 · 访问量 3154

猜你喜欢

转载自blog.csdn.net/weixin_43700342/article/details/105199038