SpringBoot异步线程配置(@EnableAsync、@Async )

SpringBoot异步线程配置

1. 配置文件
#异步线程配置
async:
  executor:
    #设置核心线程数
    corePoolSize: 10
    #设置最大线程数
    maxPoolSize: 100
    #设置队列容量
    queueCapacity: 1000
    #设置线程活跃时间(秒)
    keepAliveSeconds: 60
    #设置默认线程名称
    threadNamePrefix: xpf-thread-

2.配置类
package com.xpf.config.executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
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;

/**
 * @Title:AsyncConfig
 * @Package:com.xpf.config.executor
 * @Author: xiapf
 * @Date:2019/11/12
 * @Descrption: 开启异步线程
 */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Value("${async.executor.corePoolSize}")
    private Integer corePoolSize;
    @Value("${async.executor.maxPoolSize}")
    private Integer maxPoolSize;
    @Value("${async.executor.queueCapacity}")
    private Integer queueCapacity;
    @Value("${async.executor.keepAliveSeconds}")
    private Integer keepAliveSeconds;
    @Value("${async.executor.threadNamePrefix}")
    private String threadNamePrefix;

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 设置默认线程名称
        executor.setThreadNamePrefix(threadNamePrefix);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //初始化
        executor.initialize();

        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}
3.使用
@Async //标注为异步任务,在执行此方法的时候,会单独开启线程来执行  
public void test(){
    //操作
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zarathusa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值