2016-07-29 65 views
0

我有一個處理許多並行請求的異步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()); 
     } 

    } 
+0

可能的重複:http://stackoverflow.com/questions/22743803/servlet-with-java-lang-illegalstateexception-cannot-forward-after-response-has –

+0

@PiotrWilkin:我沒有使用「轉發」。我會稍後發佈我的代碼片段。 – HackerDuck

+0

@PiotrWilkin:我更新了我的線程。在你提供的錯誤原因中,線程指定爲:'在響應被提交到客戶端之前調用forward'。然而,我不明白我在代碼中使用'forward'的位置......特別是,我不明白爲什麼X請求被成功處理,只有這樣纔會出現問題。 – HackerDuck

回答

1

好吧,從CoyoteAdapter源的相關片段如下:

 if (status==SocketEvent.TIMEOUT) { 
      if (!asyncConImpl.timeout()) { 
       asyncConImpl.setErrorState(null, false); 
      } 
     } 

所以,這是一個套接字超時,這不是正確的處理。

+0

非常感謝。我現在會檢查它。我發送Scala請求,如下所示:'val response:HttpResponse [String] = Http(url).timeout(connTimeoutMs = 10000,readTimeoutMs = 20000000).param(param,paramValue).asString'。可能我需要更改'connTimeoutMs'。將它設置爲無限是個好主意嗎? – HackerDuck

+0

我增加了'connTimeoutMs'和'readTimeputMs'('connTimeoutMs = 1000000000,readTimeoutMs = 2000000000'),但是這個錯誤再次出現在大致相同的時刻。所以,還有一些地方我應該指定套接字超時。我應該在一些配置中將它放在REST API端嗎? – HackerDuck