SpringBoot 个人笔记-异步调用+线程池配置

本文介绍了如何在SpringBoot中使用@Async注解开启异步调用,并详细讲解了如何配置简单线程池'simpleExecutor'。通过@EnableAsync注解启用异步功能,并对线程池配置进行了探讨。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Async开启异步调用,"simpleExecutor"代表要使用的线程池

@Component
public class AsyncTest {

    @Async("simpleExecutor")
    public void test1() {
        System.out.println("异步执行test1!!!");
        System.out.println("线程id:" + Thread.currentThread().getId());
        System.out.println("线程名称:" + Thread.currentThread().getName());
    }

    @Async("commonExecutor")
    public void test2() {
        System.out.println("异步执行test2!!!");
        System.out.println("线程id:" + Thread.currentThread().getId());
        System.out.println("线程名称:" + Thread.currentThread().getName());
    }

}

 @EnableAsync 开启async功能,并扫描当前范围的配置

@EnableAsync
@SpringBootApplication
public class AsyncApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(AsyncApplication.class, args);
        AsyncTest test =(AsyncTest)context.getBean("asyncTest");
//        AsyncTest test = new AsyncTest();
        test.test1();
        test.test2();
        System.out.println("主线程执行完毕");
    }
}

线程池父类 

public abstract class ThreadPoolConfiguration {

    /**
     * 核心线程数:线程池创建时候初始化的线程数
     */
    private int corePoolSize;

    /**
     * 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
     */
    private int maxPoolSize;
    /**
     * 缓冲队列200:用来缓冲执行任务的队列
     */
    private int queueCapacity;

    /**
     * 允许线程的空闲时间(单位:秒):当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
     */
    private int keepAliveSeconds;

    /**
     * 线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
     */
    private String threadNamePrefix;

    public void setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public void setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
    }

    public void setKeepAliveSeconds(int keepAliveSeconds) {
        this.keepAliveSeconds = keepAliveSeconds;
    }

    public void setThreadNamePrefix(String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
    }

    protected AsyncTaskExecutor taskExecutor(){
        init();
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);

        // 线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    protected abstract AsyncTaskExecutor MessageExecutor();

    protected abstract int initCorePoolSize();

    protected abstract int initQueueCapacity();

    protected abstract int initKeepAliveSeconds();

    protected abstract String initThreadNamePrefix();

    /**
     * 设置线程池默认值
     */
    private void init(){
        if(corePoolSize <= 0){
            corePoolSize = initCorePoolSize();
        }
        if(maxPoolSize <= 0){
            maxPoolSize = Runtime.getRuntime().availableProcessors() + 1;
            if(corePoolSize > maxPoolSize){
                corePoolSize = maxPoolSize;
            }
        }
        if(queueCapacity <= 0){
            queueCapacity = initQueueCapacity();
        }
        if(keepAliveSeconds <= 0){
            keepAliveSeconds = initKeepAliveSeconds();
        }
        if(threadNamePrefix == null){
            threadNamePrefix = initThreadNamePrefix();
        }
    }
}

 simple线程池

@Configuration
@PropertySource(value = {"classpath:executorAsync.properties"})
@ConfigurationProperties(prefix = "simple")
public class ThreadPoolSimpleConfiguration extends ThreadPoolConfiguration {

    @Bean("simpleExecutor")
    public AsyncTaskExecutor MessageExecutor() {
        return taskExecutor();
    }

    @Override
    protected int initCorePoolSize() {
        return 6;
    }

    @Override
    protected int initQueueCapacity() {
        return 80;
    }

    @Override
    protected int initKeepAliveSeconds() {
        return 20;
    }

    @Override
    protected String initThreadNamePrefix() {
        return "simple_async_executor";
    }
}

 线程池配置信息,里面数据都有默认值,可以不配

#simple.corePoolSize=1
#simple.maxPoolSize=1
#simple.queueCapacity=200
#simple.keepAliveSeconds=20
simple.threadNamePrefix=simple_async_executor
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值