Spring Boot 异步任务

一、简介

 

二、Spring Boot异步任务

第一步:开启异步任务,启动类添加@EnableAsync

@EnableAsync
@SpringBootApplication
public class WoniuCsdnSpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(WoniuCsdnSpringbootApplication.class,args);
    }
}

第二步:创建异步任务线程池

@Slf4j
@Configuration
public class CsdnAsyncPool implements AsyncConfigurer {

    //自定义线程池,若不重写会使用默认的线程池
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(5);
        // 最大线程数
        executor.setMaxPoolSize(10);
        // 队列大小
        executor.setQueueCapacity(10);
        // 线程最大空闲时间
        executor.setKeepAliveSeconds(60);
        // 线程池中的线程的名称前缀
        executor.setThreadNamePrefix("woniu_async_");

        // 当调度器shutdown被调用时等待当前被调度的任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时长
        executor.setAwaitTerminationSeconds(60);

        /**
         线程池--拒绝策略
         ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
         ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
         ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
         ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务
         */
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.AbortPolicy()
        );

        //初始化
        executor.initialize();
        return executor;
    }

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

    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            log.info("AsyncError:{},Method:{}",throwable.getMessage(),method.getName());
            throwable.printStackTrace();
        }
    }
}

第三步:创建异步任务

@Slf4j
@Service
public class AsyncService {

    @Async("getAsyncExecutor")
    public void woniuAsync() throws InterruptedException {
        log.info("woniu async task,thread name -> {}", Thread.currentThread().getName());
    }

    @Async("getAsyncExecutor")
    public Future woniuAsyncReturn() throws InterruptedException{
        log.info("woniu async return task,thread name -> {}", Thread.currentThread().getName());
        return new AsyncResult<>("woniu");
    }
}

三、IntelliJ IDEA lombok插件的安装

参考:https://blog.csdn.net/u011374856/article/details/104551009

 

实践是检验真理的唯一标准

你可能感兴趣的:(SpringBoot)