通过配置AsyncConfigurer来实现springboot的@Async异步调用异常捕获

@Async 注解在service内的方法上(@EnableAsync开启异步),可以实现在controller的异步调用,调用的被@Async注解的方法会在一个单独线程内运行,适合即使返回,异步解耦,service慢慢去处理

@Async 注解的方法只能 返回void或者future类型的返回值,其他值会使 注解无效,因为不能异步执行

@Async 的方法在独立线程调用,不能被@ControllerAdvice全局异常处理器捕获,所以需要自己设置异常处理

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

@Configuration
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(10);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new MyAsyncUncaughtExceptionHandler();
    }
}

class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {

        System.out.println("class#method: " + method.getDeclaringClass().getName() + "#" + method.getName());
        System.out.println("type        : " + ex.getClass().getName());
        System.out.println("exception   : " + ex.getMessage());

    }
}
@Async
方法内,制作异常测试
int i=1/0;

你可能感兴趣的:(spring)