首页 > 技术文章 > SpringBoot Async异步调用/线程池

ruhuanxingyun 2019-06-04 09:17 原文

1. 概念:

  同步调用:程序按定义的顺序依次执行的过程,每一行代码执行过程必须等待上一行代码执行完毕后才执行;

  异步调用:不用等待结果的返回就执行后面的逻辑;

  比较:同步有依赖相关性,而异步没有,所以异步可并发执行,可提高执行效率,在相同的时间做更多的事情。

2. @Async、@EnableAsync注解

 

3. 自定义线程池

  A. Spring默认的线程池simpleAsyncTaskExecutor,但是实际使用ThreadPoolTaskExecutor类来创建线程池;

  B. 示例

    
package com.ruhuanxingyun.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
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;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @description: 线程池配置
 * @author: 如幻行云
 * @date: Create in 2019/6/26 9:27
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {

    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = 20;

    /**
     * 队列容量
     */
    private static final int QUEUE_CAPACITY = 1000;

    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = 50;

    /**
     * 线程活跃时间(秒)
     */
    private static final int KEEP_ALIVE_SECONDS = 300;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        threadPoolTaskExecutor.setQueueCapacity(QUEUE_CAPACITY);
        threadPoolTaskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        threadPoolTaskExecutor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        // 设置拒接策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 设置线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix("thread-pool-config-");
        // 执行初始化
        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;
    }

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

}
View Code

4. 异步回调结果

 

可参考:https://blog.lqdev.cn/2018/08/17/springboot/chapter-twenty-one/

    https://www.cnblogs.com/yw0219/p/8810956.html

推荐阅读