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

[亡魂溺海] 提交于 2019-12-18 08:58:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!