我有一个处理许多并行请求的异步REST API。在某一时刻围绕50个请求后整理加工(这个数字总是略有不同)后,我收到以下错误消息栈:java.lang.IllegalStateException:异步REST API
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:321) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311) ~[tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:349) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.catalina.core.AsyncContextImpl.setErrorState(AsyncContextImpl.java:412) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.catalina.connector.CoyoteAdapter.asyncDispatch(CoyoteAdapter.java:158) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.coyote.AbstractProcessor.dispatch(AbstractProcessor.java:222) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:53) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425) [tomcat-embed-core-8.5.4.jar:8.5.4]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.4.jar:8.5.4]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.4.jar:8.5.4]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
2016-07-29 16:36:28.505 ERROR 7040 --- [nio-8090-exec-2] o.a.c.c.C.[Tomcat].[localhost] : Exception Processing ErrorPage[errorCode=0, location=/error]
我strugelling整个一天,这个错误...问题是,我不明白其来源。不过,我觉得它有什么做的Executer
,所以我将其配置如下:
@Configuration
@SpringBootApplication
@EnableAsync
public class AppConfig {
@Bean
public javax.validation.Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(500);
executor.setMaxPoolSize(1000);
executor.setQueueCapacity(1000);
executor.setThreadNamePrefix("MyExecutor-");
executor.initialize();
return executor;
}
public static void main(String[] args) {
SpringApplication.run(AppConfig.class, args);
}
}
然而,问题依然存在。如果有人能够向我解释这个问题的原因以及如何处理这个问题,我非常感激。
UPDATE:
特别是返回以下错误:
白色标签错误页面
该应用对/错误没有 明确的映射,所以你看到这个作为 备用。
星期五07月29日16时36分28秒CEST 2016There意外错误(类型=内部服务器错误 ,状态= 500)。无消息可用
这是代码:
控制器
@RestController
@RequestMapping("/test")
public class SController {
private static long maxConcurrentRequests = 0;
@Autowired
Validator validator;
@Autowired
SAnalyzer analyzer;
/**
* Non-blocking processing
* @param docId
* @param document
* @return
*/
@RequestMapping(value = "/{docId}/getAnnotation", method = RequestMethod.GET)
public DeferredResult<Annotations> getAnnotation(@PathVariable String docId,
@RequestParam(value = "document", defaultValue = "{'id':'1','title':'bla-bla','abstract':'bla-bla','text':'bla-bla'}") String document) {
LOGGER.info("Logging output to console");
long reqId = lastRequestId.getAndIncrement();
long concReqs = concurrentRequests.getAndIncrement();
LOGGER.info("{}: Start non-blocking request #{}", concReqs, reqId);
SRequest srequest = new SRequest(SRequest.TYPE_ANNOTATION, docId, document, 1);
this.validateRequest(srequest);
// Initiate the processing in another thread
DeferredResult<Annotations> response = new DeferredResult<>();
analyzer.getAnnotation(reqId, concurrentRequests, srequest,response);
LOGGER.info("{}: Processing of non-blocking request #{} leave the request thread", concReqs, reqId);
// Return to let go of the precious thread we are holding on to...
return response;
}
private void validateRequest(SRequest request) {
DataBinder binder = new DataBinder(request);
binder.setValidator(validator);
binder.validate();
if (binder.getBindingResult().hasErrors()) {
throw new BadSysRequestException(binder.getBindingResult().toString());
}
}
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
class BadSysRequestException extends RuntimeException {
public BadSysRequestException(String message) {
super("Bad request '" + message + "'.");
}
}
TASK
@Async
@Override
public void getAnnotation(long reqId, AtomicLong concurrentRequests, SRequest request, DeferredResult<Annotations> deferredResult)
{
this.deferredResultAnnotations = deferredResult;
this.concurrentRequests = concurrentRequests;
long concReqs = this.concurrentRequests.getAndDecrement();
if (deferredResult.isSetOrExpired()) {
LOGGER.warn("{}: Processing of non-blocking request #{} already expired {}", concReqs, reqId, request.getDocument());
} else {
// result = make some heavy calculations
deferredResultAnnotations.setResult(result);
LOGGER.info("{}: Processing of non-blocking request #{} done {}", concReqs, reqId, request.getDocument());
}
}
可能的重复:http://stackoverflow.com/questions/22743803/servlet-with-java-lang-illegalstateexception-cannot-forward-after-response-has –
@PiotrWilkin:我没有使用“转发”。我会稍后发布我的代码片段。 – HackerDuck
@PiotrWilkin:我更新了我的线程。在你提供的错误原因中,线程指定为:'在响应被提交到客户端之前调用forward'。然而,我不明白我在代码中使用'forward'的位置......特别是,我不明白为什么X请求被成功处理,只有这样才会出现问题。 – HackerDuck