Rla*_*que 6 java spring multithreading
我有以下控制器建议:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(NotCachedException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ModelAndView handleNotCachedException(NotCachedException ex) {
LOGGER.warn("NotCachedException: ", ex);
return generateModelViewError(ex.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
它在大多数情况下工作得很好但是当从使用@Async注释的方法抛出NotCachedException时,异常处理不正确.
@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);
}
Run Code Online (Sandbox Code Playgroud)
这是Executor的配置:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以做些什么才能使它与@Async注释方法一起使用?
在@Async Enabled的情况下,默认的异常处理机制不起作用.要处理从使用@Async注释的方法抛出的异常,您需要实现自定义AsyncExceptionHandler.
public class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
// Here goes your exception handling logic.
}
}
Run Code Online (Sandbox Code Playgroud)
现在您需要在Application类中将此customExceptionHandler配置为
@EnableAsync
public class Application implements AsyncConfigurer {
@Override Executor getAsyncExecutor(){
// your ThreadPoolTaskExecutor configuration goes here.
}
@Override
public AsyncUncaughExceptionHandler getAsyncUncaughtExceptionHandler(){
return new AsyncExceptionHandler();
}
Run Code Online (Sandbox Code Playgroud)
注意:确保为了使AsyncExceptionHandler工作,您需要在Application类中实现AsyncConfigurer.
| 归档时间: |
|
| 查看次数: |
1570 次 |
| 最近记录: |