SpringBoot配置@Async异步线程池

参考:
springboot @Async线程默认配置
baeldung - Guide to RejectedExecutionHandler

在springBoot中可通过application.properties进行配置

#核心线程数
spring.task.execution.pool.core-size=200
#最大线程数
spring.task.execution.pool.max-size=1000
#空闲线程保留时间
spring.task.execution.pool.keep-alive=3s
#队列容量
spring.task.execution.pool.queue-capacity=1000
#线程名称前缀
spring.task.execution.thread-name-prefix=test-thread-

以上配置无法自定义拒绝策略,所以也可以通过如下代码进行配置

import com.mx.message.push.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 异步线程池配置
 *
 * @author luohq
 * @date 2019/11/20
 */
@Configuration
@EnableConfigurationProperties(AsyncProperties.class)
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
    /**
     * 异步线程池配置
     */
    private final AsyncProperties asyncProperties;

    public AsyncConfig(AsyncProperties asyncProperties) {
        this.asyncProperties = asyncProperties;
    }

    /**
     * 配置异步线程池
     *
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(this.asyncProperties.getCoreSize());
        executor.setMaxPoolSize(this.asyncProperties.getMaxSize());
        //queueCapacity Integer.Max= 21 4748 3647
        executor.setQueueCapacity(this.asyncProperties.getQueueCapacity());
        executor.setThreadNamePrefix(this.asyncProperties.getThreadNamePrefix());
        executor.setKeepAliveSeconds(this.asyncProperties.getKeepAlive());
        /** 拒绝异常处理 - 在调用线程中执行(当线程池中线程都以被占用且queue已满,则拒绝新提交的task,
         * 默认为ThreadPoolExecutor.AbortPolicy抛出异常到上层应用 - 导致异步调用死掉,无法再处理新任务,
         * 此处实现照搬ThreadPoolExecutor.CallerRunsPolicy且添加日志记录
         * */
        executor.setRejectedExecutionHandler((r, e) -> {
            log.error("Async thread pool over load - caller run - queue.size={} - 请devops人员考虑扩展服务实例", e.getQueue().size());
            if (!e.isShutdown()) {
                r.run();
            }
        });
        //如果不初始化,导致找到不到执行器(此语句需放到最后)
        executor.initialize();
        return executor;
    }

    /**
     * 异步线程池 - 全局异常处理
     *
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            log.info("Async method: {} has uncaught exception, params:{}", method.getName(), JsonUtils.toJson(params), ex);
        };
    }
}
/**
 * 异步线程池 - 属性
 *
 * @author luohq
 * @date 2021-01-26
 */
@ConfigurationProperties(prefix = "async.thead.pool")
@Data
public class AsyncProperties {

    /**
     * 核心线程池大小
     */
    private Integer coreSize;
    /**
     * 最大线程池大小
     */
    private Integer maxSize;
    /**
     * 线程池队列容量(默认Integer.MAX_VALUE)
     */
    private Integer queueCapacity;
    /**
     * 线程池空闲时长(秒)
     */
    private Integer keepAlive;
    /**
     * 线程池名称
     */
    private String threadNamePrefix;
}

在springBoot启动类上添加注解 @EnableAsync

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * SpringBoot启动类
 *
 * @author luohq
 * @date 2021-02-01
 */
@SpringBootApplication
@EnableAsync
@MapperScan("com.mx.message.push.mapper")
public class MxMessagePushMqttApplication {

    public static void main(String[] args) {
        SpringApplication.run(MxMessagePushMqttApplication.class, args);
    }

}

在想要异步执行的方法上添加注解 @Async
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

罗小爬EX

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

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

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

打赏作者

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

抵扣说明:

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

余额充值