xm
2024-06-14 722af26bc6fec32bb289b1df51a9016a4935610f
提交 | 用户 | 时间
722af2 1 package com.dl.framework.config;
X 2
3 import cn.hutool.core.util.ArrayUtil;
4 import com.dl.common.exception.ServiceException;
5 import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
6 import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.beans.factory.annotation.Qualifier;
8 import org.springframework.context.annotation.Configuration;
9 import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
10 import org.springframework.scheduling.annotation.EnableAsync;
11
12 import java.util.Arrays;
13 import java.util.concurrent.Executor;
14 import java.util.concurrent.ScheduledExecutorService;
15
16 /**
17  * 异步配置
18  *
19  * @author Lion Li
20  */
21 @EnableAsync(proxyTargetClass = true)
22 @Configuration
23 public class AsyncConfig extends AsyncConfigurerSupport {
24
25     @Autowired
26     @Qualifier("scheduledExecutorService")
27     private ScheduledExecutorService scheduledExecutorService;
28
29     /**
30      * 自定义 @Async 注解使用系统线程池
31      */
32     @Override
33     public Executor getAsyncExecutor() {
34         return scheduledExecutorService;
35     }
36
37     /**
38      * 异步执行异常处理
39      */
40     @Override
41     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
42         return (throwable, method, objects) -> {
43             throwable.printStackTrace();
44             StringBuilder sb = new StringBuilder();
45             sb.append("Exception message - ").append(throwable.getMessage())
46                 .append(", Method name - ").append(method.getName());
47             if (ArrayUtil.isNotEmpty(objects)) {
48                 sb.append(", Parameter value - ").append(Arrays.toString(objects));
49             }
50             throw new ServiceException(sb.toString());
51         };
52     }
53
54 }