我正在使用 Spring boot 应用程序。我有一个返回 Callable 的休息控制器。
@GetMapping("/fb-roles")
@Timed
public Callable<List<FbRole>> getAllFbRoles() {
log.debug("REST request to get all FbRoles");
return (() -> { return fbRoleRepository.findAll(); });
}
ThreadPoolTaskExecutor 配置如下:
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final JHipsterProperties jHipsterProperties;
public AsyncConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
executor.setThreadNamePrefix("fb-quiz-Executor-");
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
2018-09-19 00:43:58.434 警告 10104 --- [ XNIO-2 任务 28] o.s.w.c.request.async.WebAsyncManager :
!!!
需要 Executor 来处理 java.util.concurrent.Callable 返回值。
请在 MVC 配置中的“异步支持”下配置一个 TaskExecutor。
当前使用的SimpleAsyncTaskExecutor不适合在负载下使用。
但是在访问 api 服务器时会产生以下警告
Spring 配置在这方面有点令人困惑,因为它需要单独配置 MVC 异步支持,即使用返回Callable
,并且对于任何带有注释的 Spring bean 方法@Async
。要正确配置两者,您可以应用类似于下面的配置的内容,请记住AsyncTaskExecutor
配置可能需要修改:
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Bean
protected WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(getTaskExecutor());
}
};
}
@Bean
protected ConcurrentTaskExecutor getTaskExecutor() {
return new ConcurrentTaskExecutor(Executors.newFixedThreadPool(5));
}
}
附带说明一下,您可能会想简单地用以下注释来注释您的控制器处理程序方法@Async
。这只会产生预期的效果——释放 Web 服务器线程——即发即忘操作(此观察基于 Spring Boot 2.1.2,可能他们将来会解决此问题)。如果你想利用Servlet 3.0 异步处理,你真的必须使用Callables
并配置它们WebMvcConfigurer
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)