我尝试从 WebClient 替换 RestTemplate,因为根据 Java Doc,将不推荐使用 RestTemplate。Spring 团队建议尽可能使用 WebClient。
RestTempalte 之前的代码如下
public Map<String,String> getInfo()
{
HttpHeaders headers = new HttpHeaders();
headers.set( ACCEPT, MediaType.APPLICATION_JSON_VALUE );
HttpEntity<?> entity = new HttpEntity<>( headers );
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( this.endpoint + VERSION_INFO_PATH );
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<CPResponse> response = restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
entity,
CPResponse.class );
List<Object> resultList = response.getBody().getResults();
if( response.getBody().getResults() != null && !( resultList )
.isEmpty() )
{
return ( ( LinkedHashMap ) resultList.get( 0 ) );
}
else
{
throw new CrawlerRuntimeExceptions( "Invalid response from API" );
}
}
我想从 WebClient 替换 RestTemplate。所以我实现类 WebClientConnection 如下
public class WebClientConnection
{
private WebClient webClient;
public WebClientConnection( String baseUrl )
{
this.webClient = WebClient.create( baseUrl );
}
public Mono<CPResponse> get( String url )
{
return webClient.get().uri( "/{url}",url ).retrieve().bodyToMono( CPResponse.class );
}
public Flux<CPResponse> getAll( String url )
{
return webClient.get().uri( "/{url}",url ).retrieve().bodyToFlux( CPResponse.class );
}
public Mono<CPResponse> post( String url, HttpEntity entity )
{
return webClient.post().uri( "/{url}",url ).retrieve().bodyToMono( CPResponse.class );
}
}
我使用这个依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>>2.1.3.RELEASE</version>
</dependency>
public void getInfo()
{
WebClientConnection webClientConnection = new WebClientConnection( endpoint );
Mono<CPResponse> response = webClientConnection.get( VERSION_INFO_PATH );
}
webclient创建时出现stackOverflow错误
public WebClientConnection( String baseUrl )
{
this.webClient = WebClient.create( baseUrl );
}
如何正确执行从 RestTemplate 到 WebClient 的迁移?