简体   繁体   中英

Only one connection receive subscriber allowed

Can someone help me with Only one connection receive subscriber allowed. error?

I looked at Oleh Dokuka's answer but it did not help me.

I have simplified the code for demonstration purpose. In my actual code I am getting a bulk Json request, I need to query two different tables taking two different parameters from the request body, call another service using both the results and send the result in the response.

Router function

@Bean
    public RouterFunction<ServerResponse> myRoute(MyRequestHandler myRequestHandler) {

        return route(RequestPredicates.POST("/api/something"), myRequestHandler::myHandlerFunction);
    }

Handler function

public Mono<ServerResponse> myHandlerFunction(ServerRequest serverRequest) {
        Mono<Integer> just = Mono.just(22);

//For simplification I've added String body here. In actual code I have proper json body 
        Mono<String> stringMono = serverRequest.bodyToMono(String.class);

        Mono<String> mono = stringMono.zipWith(stringMono).map(t -> t.getT2() + t.getT1());

        return ok().body(mono, String.class);
    }

The code is working fine if I replace stringMono with just in both the places in

Mono<String> mono = stringMono.zipWith(stringMono).map(t -> t.getT2() + t.getT1());

Why is it working with Mono<String> mono = just.zipWith(just).map(t -> t.getT2() + t.getT1());

Thanks in advance.

It looks like the stringMono.zipWith(stringMono) will cause Spring to attempt to subscribe to the body of the request twice which is likely your problem since the ServerRequest is unicast and can have only one subscriber.

Try this:

Mono<String> stringMono = serverRequest.bodyToMono(String.class).publish(body -> body.zipWith(body).map(t -> t.getT2() + t.getT1()));

publish() will not cause multiple subscriptions to the body.

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