Search code examples
springkotlinnettywebclientblocking

webclient blocking main thread netty, why?


I don't understand why webclient blocks the main netty thread I use gradle here are its dependencies:

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:Hoxton.SR11"
    }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    ...
}

This gradle script is used in both applications. In the first application, I perform:

    @GetMapping
    open fun otherApp(): Mono<String> {
        return WebClient.create("http://localhost:8081")
                .get()
                .uri("/test")
                .retrieve()
                .bodyToMono(String::class.java)
//              I tried to use an additional scheduler but the main stream is blocked with it too
//              .publishOn(Schedulers.boundedElastic())
    }

The second application emulates a long response processing:

@GetMapping("/test")
    open fun test(): Mono<String> {
        Thread.sleep(15000L)
        return Mono.just("Hello");
    }

And I expect that the calling service will not block the main thread, but will continue to process incoming connections, but until I get a response from the first call(sleep will work), my next connections are hanging in wait.

Result: The first application works like tomcat with a single thread

My question: What do i wrong?


Solution

  • The client application does not block, it is able to process new requests. You can confirm that by adding logs:

    @GetMapping("/test")
    public Mono<String> test() {
        return Mono.just("incoming request")
            .doOnNext(e -> logger.info("Process: {}", e))
            .flatMap(e -> webclient.test());
    }
    

    The server application is blocked because Thread.sleep(15000L) blocks the main thread (consider using .delayElement(Duration.ofSeconds(15)) instead)

    If the issue happens for requests originated by a web browser

    It is due to the browser cache. You should disable caching or force a hard refresh(CTRL + F5).

    I tested the hard refresh and it seems to work fine.