java - Spring @ExceptionHandler 和多线程

标签 java spring multithreading

我有以下 Controller 建议:

@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(NotCachedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ModelAndView handleNotCachedException(NotCachedException ex) {
        LOGGER.warn("NotCachedException: ", ex);
        return generateModelViewError(ex.getMessage());
    }

}

它在大多数情况下工作得很好,但是当 NotCachedException 从使用 @Async 注释的方法中抛出时,异常没有得到正确处理。

@RequestMapping(path = "", method = RequestMethod.PUT)
@Async
public ResponseEntity<String> store(@Valid @RequestBody FeedbackRequest request, String clientSource) {
    cachingService.storeFeedback(request, ClientSource.from(clientSource));
    return new ResponseEntity<>(OK);
}

这是执行器的配置:

@SpringBootApplication
@EnableAsync
public class Application {

private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        SettingsConfig settings = context.getBean(SettingsConfig.class);
        LOGGER.info("{} ({}) started", settings.getArtifact(), settings.getVersion());
        createCachingIndex(cachingService);
    }

    @Bean(name = "matchingStoreExecutor")
    public Executor getAsyncExecutor() {
        int nbThreadPool = 5;
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(nbThreadPool);
        executor.setMaxPoolSize(nbThreadPool * 2);
        executor.setQueueCapacity(nbThreadPool * 10);
        executor.setThreadNamePrefix("matching-store-executor-");
        executor.initialize();
        return executor;
    }

}

我该怎么做才能使其与带@Async 注释的方法一起使用?

最佳答案

默认的异常处理机制在启用@Async 的情况下不起作用。 要处理从使用 @Async 注释的方法抛出的异常,您需要将自定义 AsyncExceptionHandler 实现为。

public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{
    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        // Here goes your exception handling logic.

    }
}

现在您需要在应用程序类中将此 customExceptionHandler 配置为

@EnableAsync
public class Application implements AsyncConfigurer {
     @Override Executor getAsyncExecutor(){
      // your ThreadPoolTaskExecutor configuration goes here. 
}


@Override
public AsyncUncaughExceptionHandler getAsyncUncaughtExceptionHandler(){
   return new AsyncExceptionHandler();
}

注意:确保为了使 AsyncExceptionHandler 正常工作,您需要在 Application 类中实现 AsyncConfigurer。

关于java - Spring @ExceptionHandler 和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138199/

相关文章:

java - 如何仅在特定配置文件上启用 spring 基本身份验证?

java方法同步对象

python - 为每个进程划分一个for循环

java - 在hibernate中使用主键和外键组合映射三个表

java - 获取葡萄牙语 - Android

class - JDK中是否有一个类来表示一天中的一个小时,但不一定是特定日期的特定时间?

java - 使用可变参数绘制星形

java - 修改Java单元测试中多个bean中使用的参数值

java - 如何将代理注入(inject)服务?

C#:关于成员变量线程安全的问题