问题
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)
回答1:
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);
回答2:
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;
}
来源:https://stackoverflow.com/questions/41396430/spring-5-web-reactive-how-can-we-use-webclient-to-retrieve-streamed-data-in-a