[英]How to make a synchronous call with WebClient using Open API Code Generator
RestTemplate 文檔中的 Spring 有注釋:
從 5.0 開始,class 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);
}
預期 Output(類似於 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 而不對當前代碼進行任何重大更改
您希望生成 Rest 模板類,但您使用的是<library>webclient</library>
,請更改為<library>resttemplate</library>
在此處閱讀整個文檔https://openapi-generator.tech/docs/generators /java/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.