【问题标题】:how to turn rest controller in async controller?如何在异步控制器中打开休息控制器?
【发布时间】:2021-07-13 17:03:49
【问题描述】:

我们的项目中有一个平均在 30 秒内返回的端点, 因此,我们建议将此端点设为异步

但是,使用时服务不再工作

@PostMapping("/alocacaoPorPeriodo")
public void alocacaoPorPeriodo(@RequestParam(required = true) Date dataInicio, @RequestParam(required = true)  Date dataFim) {
    CompletableFuture.runAsync(() -> alocacaoServive.alocarPorPeriodo(dataInicio, dataFim));
}

服务调用从 jpa 存储库中删除、保存或更新方法时发生错误。获取方法仍然有效。

No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

这是我们为实现异步所做的独特更改,我是不是忘记了什么?

谢谢

【问题讨论】:

  • 你的班级有@EnableAsync吗?
  • 您可能在您的服务中使用RequestContextHolder.getCurrentRequestAttributes() 或请求范围的对象。

标签: java spring hibernate jpa


【解决方案1】:

你确定你没有在任何地方覆盖/操作 HttpServletRequest 吗?如果你这样做了,请看一下:java.lang.IllegalStateException: No thread-bound request found, exception in aspect

一个简单的工作场景如下

请求:

curl -X POST "http://localhost:8080/?dataInicio=1996-01-05&dataFim=1996-01-01" -H "accept: */*" 

代码:

 @PostMapping
  public ResponseEntity doItAsync(
      @RequestParam(required = true)
      @DateTimeFormat(pattern="yyyy-MM-dd") Date dataInicio,
      @RequestParam(required = true)
      @DateTimeFormat(pattern="yyyy-MM-dd")
          Date dataFim) {
    LocalDateTime requestDate= LocalDateTime.now();
    Runnable task2 = simpleRunnable(requestDate,dataInicio, dataFim);
    // start the thread
    new Thread(task2).start();
    //202 accepted response...
    return ResponseEntity.accepted().build();
  }

  private Runnable simpleRunnable(LocalDateTime requestDate, Date dataInicio, Date dataFim) {
    Runnable task2 = () -> {
      //delay 5 Second
      delayInSecond(5);
      log.info("\n Request Start at:{}\n dataInicio:{} ,\ndataFim: {},\n request end At:{}",requestDate,dataInicio, dataFim,LocalDateTime.now());
    };
    return task2;
  }

  private void delayInSecond(int second) {
    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      log.error(e.getMessage());
    }
  }

输出:

2021-07-12 23:21:46,776 INFO  [Thread-3]  [lambda$simpleRunnable$0:99]: 
 Request Start at:2021-07-12T23:21:41.769142
 dataInicio:Fri Jan 05 00:00:00 TRT 1996 ,
 dataFim: Mon Jan 01 00:00:00 TRT 1996,
 request end At:2021-07-12T23:21:46.776494

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 2018-04-19
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多