0

we have in our project a endpoint that returns in 30 seconds avg, for this reason, we suggest turn this endpoint in async

but, the services is not working anymore when using

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

The error happens when service call delete, save or update methods from jpa repository. Get methods is still working.

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.

this is the unique change that we have made to turn async, did I forget something?

thx

1 Answers1

0

Are you sure that you didn't overwrite/manipulate HttpServletRequest in anywhere? if you did, please take a look at: java.lang.IllegalStateException: No thread-bound request found, exception in aspect

A simple scenario that works is as follows

Request:

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

Code:

 @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());
    }
  }

Output:

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