a3dsfcv
a3dsfcv

Reputation: 1274

Async requests in webflux are not async

I want my request to trigger some long running action, that should be executed in the background. I wrote the following implementation that should process my action in a background, but in fact my request executed synchronously:

    @AsyncTimeout(10 * 60 * 1000)
    @PostMapping("/dosomething")
    Mono<Void> doSomething() {
        return Mono.defer(() -> delay()).subscribeOn(Schedulers.elastic());
    }

    public static Mono<Void> delay() {
        return Mono.fromRunnable(() -> {
            LOG.info("Started sleep");
            Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
            LOG.info("Finished sleep");
        });
    }

in logs I see the following:

14:29:58.801 DEBUG 1 --- [p1491676195-768] Incoming request for POST http://localhost:8989/dosomething
14:29:58.802  INFO 1 --- [      elastic-6] Started sleep
14:30:08.803  INFO 1 --- [      elastic-6] Finished sleep
14:30:08.806 DEBUG 1 --- [p1491676195-655] Outgoing response for POST http://localhost:8989/dosomething: 200

I see that my sleep is executed in another thread, but for some reason my original request waits for sleep to finish

Update 1:

    @PostMapping("/dosomething")
    Mono<Void> doSomething() {
        return Mono.defer(() -> {
            delay().subscribe();
            return Mono.empty();
        });

Upvotes: 0

Views: 2081

Answers (1)

nmina
nmina

Reputation: 286

Based on the comments I've read, and from how I understood your concern, if you are expecting to run a blocking call but run it in the background while immediately returning back a response to the service call, you can simply add the subscribeOn to that process which in your example is the delay(). This will make it run in a different thread:

@PostMapping("/dosomething")
    Mono<Void> doSomething() {
        return Mono.defer(() -> {
            delay().subscribeOn(Schedulers.boundedElastic()).subscribe();
            return Mono.empty();
        });

This link may be related to your concern: https://projectreactor.io/docs/core/release/reference/#faq.wrap-blocking

Upvotes: 2

Related Questions