简体   繁体   中英

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-5

I'm using spring boot version '2.4.5' and 'org.springframework.boot:spring-boot-starter-webflux'. When I try to execute the code below, I get the following error block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-5 I tried to use toFuture() and share() methods, but they didn't work.

    String Student = webClient.get()
            .uri("MY_URL")
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .bodyToMono(Student.class)
            .block();
    
    boolean isValid = verifyStudentInfo(student);
    
    if (isValid) {
        method1();
    } else {
        method2();
    }

In my case, I need the operation to be blocking because I will be using the result later in the code. I didn't want to use RestTemplate because it will be deprecated and I already have WebClient configuration in my project including ReactiveClientRegistrationRepository.

Is there anyway I can enable blocking operations?

Reactive apis/processes are not supposed to operate outside the publisher pipelines which are to be subscribed by the client or the browser. If you need to access a publisher's data in your api, you can use flatMap to integrate it in your publisher pipeline and drive your business logic with this which will be executed after the client subscribes to the publisher.

You can use something like this if you want to use an integer value to drive your business logic

    Mono<Void> useValFromMono() {
        return getMono().flatMap(valFromMono -> getPublisherBasedOnVal(valFromMono));
    }

    Mono<Integer> getMono() {
        return Mono.fromSupplier(() -> getInteger());
    }

    private Integer getInteger() {
        return new Random().nextInt(10);
    }

    Mono<Void> getPublisherBasedOnVal(Integer integer) {
        if(integer == 2) {
            return Mono.fromRunnable(() -> System.out.println("Its 2!"));
        }
        return Mono.empty();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM