Spring 5 Web Reactive - How can we use WebClient to retrieve streamed data in a Flux?

11.9k views Asked by At

The current milestone (M4) documentation shows and example about how to retrieve a Mono using WebClient:

WebClient webClient = WebClient.create(new ReactorClientHttpConnector());

ClientRequest<Void> request = ClientRequest.GET("http://example.com/accounts/{id}", 1L)
                .accept(MediaType.APPLICATION_JSON).build();

Mono<Account> account = this.webClient
                .exchange(request)
                .then(response -> response.body(toMono(Account.class)));

How can we get streamed data (from a service that returns text/event-stream) into a Flux using WebClient? Does it support automatic Jackson conversion?.

This is how I did it in a previous milestone, but the API has changed and can't find how to do it anymore:

final ClientRequest<Void> request = ClientRequest.GET(url)
    .accept(MediaType.TEXT_EVENT_STREAM).build();
Flux<Alert> response = webClient.retrieveFlux(request, Alert.class)
2

There are 2 answers

1
Brian Clozel On BEST ANSWER

This is how you can achieve the same thing with the new API:

final ClientRequest request = ClientRequest.GET(url)
        .accept(MediaType.TEXT_EVENT_STREAM).build();
Flux<Alert> alerts = webClient.exchange(request)
        .retrieve().bodyToFlux(Alert.class);
0
codependent On

With Spring 5.0.0.RELEASE this is how you do it:

public Flux<Alert> getAccountAlerts(int accountId){
    String url = serviceBaseUrl+"/accounts/{accountId}/alerts";
    Flux<Alert> alerts = webClient.get()
        .uri(url, accountId)
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToFlux( Alert.class )
        .log();
    return alerts;
}