用webClient替换restTemplate

问题描述 投票:0回答:1

我有一个控制器,使用RestTemplate从几个休息端点获取数据。由于'RestTemplate'被阻止,我的网页需要很长时间才能加载。为了提高性能,我打算用RestTeamplate替换所有的Spring WebClient。我目前使用RestTemplate的方法之一如下。

public List<MyObject> getMyObject(String input){
    URI uri = UriComponentsBuilder.fromUriString("/someurl")
            .path("123456")
            .build()
            .toUri();
    RequestEntity<?> request = RequestEntity.get(uri).build();
    ParameterizedTypeReference<List<MyObject>> responseType =   new ParameterizedTypeReference<List<MyObject>>() {};
    ResponseEntity<List<MyObject>> responseEntity = restTemplate.exchange(request, responseType); 

    MyObject      obj= responseEntity.getBody(); 

}

现在我想替换上面的方法来使用WebClient,但我是WebClient的新手,不知道从哪里开始。任何方向和帮助表示赞赏。

resttemplate spring-webflux spring-webclient
1个回答
2
投票

为了帮助您,我将举例说明如何使用webClient替换restTemplate。我希望你已经设置了你的pom.xml

创建了一个Configuration类。

@Slf4j
@Configuration
public class ApplicationConfig {

    /**
     * Web client web client.
     *
     * @return the web client
     */
    @Bean
    WebClient webClient() {
        return WebClient.builder()
            .filter(this.logRequest())
            .filter(this.logResponse())
            .build();
    }

    private ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
            log.info("WebClient request: {} {} {}", clientRequest.method(), clientRequest.url(), clientRequest.body());
            clientRequest.headers().forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
            return Mono.just(clientRequest);
        });
    }

    private ExchangeFilterFunction logResponse() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            log.info("WebClient response status: {}", clientResponse.statusCode());
            return Mono.just(clientResponse);
        });
    }
}

另外还有一个调用WebClient的服务类

@Component
@RequiredArgsConstructor
public class MyObjectService {

    private final WebClient webClient;

    public Mono<List<Object>> getMyObject(String input) {
        URI uri = UriComponentsBuilder.fromUriString("/someurl")
            .path("123456")
            .build()
            .toUri();

        ParameterizedTypeReference<List<MyObject>> responseType = new ParameterizedTypeReference<List<MyObject>>() {
        };

        return this.webClient
            .get()
            .uri(uri)
            .exchange()
            .flatMap(response -> response.bodyToMono(responseType));
    }
}

这将给你一个非阻塞的List<MyObject>单声道,你也可以通过使用response.bodyToFlux(responseType)提取身体到助焊剂

我希望这会为你提供一个探索更多的基础。

© www.soinside.com 2019 - 2024. All rights reserved.