@Async 注解自定义线程池进行使用

@Async 自定义线程池

自定义线程池逻辑

/**
 * @author Greenarrow
 * @date 2023/9/22
 * @description @Async 自定义线程池
 */
@Component
@Slf4j
public class ThreadPoolConfig implements AsyncConfigurer {

    /**
     * 阻塞系数 0-1 越大线程数越多
     */
    private static final float BLOCKING_COEFFICIENT = 0.85F;
    /**
     * 默认线程池配置 TODO 可改为配置项
     * @return
     */
    @Override
    @Bean(CommonConstant.ASYNC_EXECUTOR_CUSTOM)
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        int poolSize = (int) (Runtime.getRuntime().availableProcessors() / (1 - BLOCKING_COEFFICIENT));
        threadPool.setCorePoolSize(poolSize);
        threadPool.setMaxPoolSize(poolSize);
        threadPool.setQueueCapacity(poolSize*2);
        threadPool.setKeepAliveSeconds(60);
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        threadPool.setAwaitTerminationSeconds(60 * 15);
        threadPool.setThreadNamePrefix("async-task-thread-pool-");
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPool.initialize();
       log.info(">>>>>>>>>>>>>>> 开启自定义异步线程池");
        return threadPool;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncExceptionHandler();
    }
    /**
     * 自定义异常处理类
     *
     *
     */
    static class MyAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

        //手动处理捕获的异常
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
            log.error(">>>>>>>>>>>>>>> 自定义线程池捕获线程异常信息 {}",throwable.toString());
            log.error("Exception message - " + throwable.getMessage());
            log.error("Method name - " + method.getName());
            for (Object param : obj) {
                log.info("Parameter value - " + param);
            }
        }

    }
}

使用

@Async(CommonConstant.ASYNC_EXECUTOR_CUSTOM)

其他

    /**
     * 自定义线程池名称
     */
    public static final String ASYNC_EXECUTOR_CUSTOM = "async-executor-custom";
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值