优惠券-异步任务

90 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第30天,点击查看活动详情

1.pom.xml引入依赖

image.png

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.启动类添加开启异步注解

image.png

3.创建异步包(Async)并且新建AsynService类

image.png

4.编辑AsyncService类

image.png

@Slf4j
@Service
public class AsyncService {

    @Async
    //无返回值的异步任务
    public void asyncProcess() throws InterruptedException{
        log.info("async process task ,current thread name {}",Thread.currentThread().getName());
        TimeUnit.SECONDS.sleep(2);
    }

    @Async
    //定义有返回值的异步任务
    public Future<Integer> asyncProcessHasReturn() throws InterruptedException{
        log.info("async process task has return ,current thread name {}",Thread.currentThread().getName());
        TimeUnit.SECONDS.sleep(2);
        return  new AsyncResult<>(100);
    }
}

========================

5.config新增AsyncPoolConfig线程池配置文件

image.png

@Slf4j
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {
    @Bean
    @Override
    public Executor getAsyncExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(20);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("ImoocAsync_");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        //拒绝器
        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:{},Param:{}",throwable.getMessage(),method.getName(), JSON.toJSONString(objects));
            throwable.printStackTrace();
            //发送邮件或者短信
        }
    }

代码说明:

  • @Configuration:注入配置类

  • class AsyncPoolConfig implements AsyncConfigurer:线程池配置类实现AsyncConfigurer

  • setCorePoolSize:核心线程池大小

  • setMaxPoolSize:线程池中允许的最大线程数

  • setQueueCapacity:线程池中使用的缓冲队列大小

  • setKeepAliveSeconds:空闲线程存活时间

  • setThreadNamePrefix:线程名称前缀

  • setWaitForTasksToCompleteOnShutdown:该方法用来设置线程池关闭的时候等待所有任务都完成后,再继续销毁其他的Bean,这样这些异步任务的销毁就会先于数据库连接池对象的销毁

  • setAwaitTerminationSeconds(60):** 该方法用来设置线程池中 任务的等待时间,如果超过这个时间还没有销毁就 强制销毁,以确保应用最后能够被关闭,而不是阻塞住。

  • setRejectedExecutionHandler:拒绝器策略
    image.png

  • executor.initialize():初始化线程池

  • AsyncUncaughtExceptionHandler:异步线程异常类

  • public void handleUncaughtException(Throwable throwable, Method method, Object... objects):重写异常类,可以捕获无返回值的异常