2021-02-06-Spring Boot uses multithreading examples

purpose

  • This document is to use multi-threading to open a single thread to do some things in the business (such as sending emails), in order to achieve the purpose of improving the running speed of the overall project

Main start class

  • First use @EnableAsync to enable Springboot's support for asynchronous tasks
@EnableAsync
public class TzsbxtApplication  extends SpringBootServletInitializer  {

Configuration class

  • The configuration class implements the interface AsyncConfigurator and returns a ThreadPoolTaskExecutor thread pool object.
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
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.util.concurrent.Executor;

/**
 * @author qinchunlin
 * @version 1.0.0
 * @ClassName AsyncTaskConfig
 * @Description
 * @createTime 2021年01月06日 14:18:00
 */
@Configuration
@EnableAsync
public class AsyncTaskConfig implements AsyncConfigurer {

    // ThredPoolTaskExcutor的处理流程
    // 当池子大小小于corePoolSize,就新建线程,并处理请求
    // 当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去workQueue中取任务并处理
    // 当workQueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize,就用RejectedExecutionHandler来做拒绝处理
    // 当池子的线程数大于corePoolSize时,多余的线程会等待keepAliveTime长时间,如果无请求可处理就自行销毁

    @Override
    @Bean
    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;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

Call based on @Async without return value

  • The @Async annotation indicates that the method is an asynchronous method. If the annotation is on a class, it indicates that all methods in this class are asynchronous.
 @Async
    public void executeAsyncMail(String body) {
      System.out.println("写执行内容");
    }

Call based on @Async return value

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41270550/article/details/113725651