Spring异步Async的配置

  1. 编写线程池配置类
    @Slf4j
    @EnableAsync
    @Configuration
    public class AsyncConfig implements AsyncConfigurer {
        // 注意这里需要使用
        @Bean
        @Override
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
            threadPool.setCorePoolSize(50);
            threadPool.setMaxPoolSize(100);
            threadPool.setKeepAliveSeconds(10);
            threadPool.setQueueCapacity(1000);
            threadPool.setThreadNamePrefix("custom-task-pool-");
            //
            threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            threadPool.setAwaitTerminationSeconds(5);
            threadPool.setWaitForTasksToCompleteOnShutdown(true);
            threadPool.initialize();
            return threadPool;
        }
        /**
         * 1. 当方法返回Future<T>,手动调用feature.get则不会回调handleUncaughtException方法
         * 2. 当方法返回Future<T>时,如果不调用手动调用feature.get则异常无法正常抛出
         */
        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return new CustomAsyncUncaughtExceptionHandler();
        }
        /**
         * 自定义异步异常处理器
         */
        static class CustomAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                //此demo只打印日志,实际项目以具体业务需求来处理
                log.error(">>> CustomAsyncUncaughtExceptionHandler,class:{}, method: {}, params: {}, error: {}",
                        method.getDeclaringClass().getSimpleName(), method.getName(), Arrays.toString(params),
                        ex.getMessage());
            }
        }
    }
    
  2. 编写业务验证方法(方法上使用@Async注解标注)
    @Slf4j
    @Service
    public class AsyncServiceImpl {
        @Async("getAsyncExecutor")
        public Future<String> asyncImport(List<String> list, String taskId) {
            log.info("异步导入工作进行中, 请耐性等待...");
            if (list.size() > 10){
                int i = 1 / 0;
            }
            CommonUtil.sleepQuiet(2000);
            String uuid = CommonUtil.uuid();
            return new AsyncResult<>(uuid) ;
        }
        @Async("getAsyncExecutor")
        public void asyncImportVoid(List<String> list, String taskId) {
            log.info("异步导入工作进行中, 请耐性等待...");
            if (list.size() > 10){
                int i = 1 / 0;
            }
            CommonUtil.sleepQuiet(3000);
        }
    }
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值