Spring @Async vs Spring WebFlux

Viewed 336

I'm trying to convert the following method using WebFlux to avoid using @Async on the same.

@Async
@Override
public void notifyCallback(NotifyCallbackRequest request, String id) {

        startProcess(id);

}

Controller class:

@ResponseStatus(HttpStatus.OK)
@PostMapping("/notify-status/{id}")
public void notifyCallback(@PathVariable("id") String id, @RequestBody NotifyCallbackRequest request) {
    identityService.notifyCallback(request, id);
}

startProcess(id) is a method that makes an api call via webflux and returns a Mono type. I am interested that the caller immediately receives a ResponseStatus (HttpStatus.OK) despite what happens next.

1 Answers

You can just subscribe to your "async" task independently of your main reactive chain to start to make it run in the background as soon as the endpoint is called.

@Override
public void notifyCallback(NotifyCallbackRequest request, String id) {
        startProcess(id).subscribe();
}

@ResponseStatus(HttpStatus.OK)
@PostMapping("/notify-status/{id}")
public Mono<Void> notifyCallback(@PathVariable("id") String id, @RequestBody NotifyCallbackRequest request) {
    identityService.notifyCallback(request, id);
    return Mono.empty();
}

You can demo this behaviour using the following endpoint example. If you call the endpoint, it will a 200 straight away and 10 seconds later it will log to your console

@RequestMapping(path = "/async", method = RequestMethod.GET)
public Mono<Void> start() {
    Mono.delay(Duration.ofSeconds(10))
            .doOnNext(i -> LOGGER.info("we have waited 10 seconds"))
            .subscribe();

    return Mono.empty();
} 
Related