ssslinppp

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

堵塞Controller

  1. Controller为单例;
  2. 非线程安全;
  3. 堵塞方式;
  4. 1个request对应1个处理Thread;
@RestController
public class ProcessingController {

  @RequestMapping("/process-blocking")
  public ProcessingStatus blockingProcessing(...) {
    ...
    return new ProcessingStatus(...);
  }
}

时序图

测试结果

非阻塞

@RestController
public class ProcessingController {

  @RequestMapping("/process-non-blocking")
  public DeferredResult<ProcessingStatus> nonBlockingProcessing(...) {

    // Initiate the processing in another thread
    DeferredResult<ProcessingStatus> deferredResult = new DeferredResult<>();
    ProcessingTask task = new ProcessingTask(deferredResult, ...);
    dispatch(task);

    // Return to let go of the precious thread we are holding on to...
    return deferredResult;
  }
}


public class ProcessingTask extends SomeCallbackInterface {

  private DeferredResult<ProcessingStatus> deferredResult;

  public ProcessingTask(DeferredResult<ProcessingStatus> deferredResult, ...) {
    this.deferredResult = deferredResult;
    ...
  }

  @Override
  public void done() {
    if (deferredResult.isSetOrExpired()) {
      LOG.warn("Processing of non-blocking request already expired");
    } else {
      boolean deferredStatus = deferredResult.setResult(new ProcessingStatus(...));
    }
  }
}

THE EXTERNAL RESOURCE API IS ALSO NON-BLOCKING

THE EXTERNAL RESOURCE API IS BLOCKING.

测试结果


原文链接

Developing non-blocking REST services with Spring MVC

posted on 2018-02-24 12:42  ssslinppp  阅读(254)  评论(0编辑  收藏  举报