RestTemplate 文档中的 Spring 有注释:
从 5.0 开始,类 org.springframework.web.client.RestTemplate 处于维护模式,只有较小的更改请求和错误被接受。请考虑使用 org.springframework.web.reactive.client.WebClient,它具有更现代的 API 并支持同步、异步和流式处理方案
当我尝试使用 Open Api 代码生成器将 RestTemplate 替换为 WebClient 时,我无法进行同步调用。
pom.xml 代码
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>${openapi-tool-version}</version>
<executions>
<execution>
<id>Games</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<generatorName>java</generatorName>
<library>webclient</library>
<inputSpec>${project.basedir}/spec/games.yaml</inputSpec>
<configOptions>
<configPackage>com.tintin.config</configPackage>
<apiPackage>com.tintin.api</apiPackage>
<modelPackage>com.tintin.model</modelPackage>
<invokerPackage>com.tintin.service</invokerPackage>
<sourceFolder>src/main/java</sourceFolder>
<dateLibrary>java8</dateLibrary>
</configOptions>
<generateModelTests>false</generateModelTests>
<generateApiTests>false</generateApiTests>
</configuration>
</execution>
</executions>
</plugin>
默认情况下,webclient 进行异步调用并将响应包装在 Mono<> 中。
public <T> Mono<T> invokeAPI(String path, HttpMethod method, Map<String, Object> pathParams, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames);
return requestBuilder.retrieve().bodyToMono(returnType);
}
预期输出(类似于 resttemplate)
public <T> ResponseEntity<T> invokeAPI(String path, HttpMethod method, Map<String, Object> pathParams, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames);
return requestBuilder.retrieve().bodyToMono(returnType).block();
}
如何使用开放的 api 代码生成器将 Resttemplate 替换为 Webclient 而不对当前代码进行任何重大更改