3

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)
4

2 回答 2

7

使用 Spring 5.0.0.RELEASE,您可以这样做:

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;
}
于 2017-08-04T09:16:32.343 回答
7

这就是您可以使用新 API 实现相同目标的方法:

final ClientRequest request = ClientRequest.GET(url)
        .accept(MediaType.TEXT_EVENT_STREAM).build();
Flux<Alert> alerts = webClient.exchange(request)
        .retrieve().bodyToFlux(Alert.class);
于 2017-01-07T16:34:51.723 回答