WebClient 错误地尝试启动 Web 服务器

WebClient is incorrectly trying to start a web server

我正在尝试迁移我的 REST 客户端应用程序以使用 WebClient 而不是 RestTemplate。 但是,当我 运行 我的客户端代码时,它显然正在尝试启动 Web 服务器并连接到端口 8080,但失败了,因为 Tomcat 已经 运行 在该端口上。

我不想启动网络服务器。我只想连接到外部 Web 服务器并拉回响应。

这是我得到的错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Web server failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

这是我的测试代码:

package test.rest.webClient;

import java.util.Map;
import org.apache.hc.core5.net.URIBuilder;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersUriSpec;
import org.springframework.web.reactive.function.client.WebClient.ResponseSpec;
import reactor.core.publisher.Mono;
import test.Path;

@SpringBootApplication
public class WebClientTest implements CommandLineRunner {
  @Override
  public void run(String... args) 
  throws Exception {
    URIBuilder builder = new URIBuilder();
    builder.setScheme("https");
    builder.setHost("marketing.propfinancing.com");
    builder.setPath("/caddata/TXCollin/getByIdAndYear");
    builder.addParameter("id", "37");
    builder.addParameter("year", "2022");

    WebClient client = WebClient.create();
    RequestHeadersUriSpec<?> uriSpec = client.get();
    uriSpec.uri(builder.build());
    uriSpec.header(Path.getApplicationProperties().getProperty("caddata.apiKey.header.name"), 
        Path.getApplicationProperties().getProperty("caddata.apiKey"));
    uriSpec.accept(MediaType.APPLICATION_JSON);
    ResponseSpec responseSpec = uriSpec.retrieve();
    ParameterizedTypeReference<Map<String,Object>> typeReference = new ParameterizedTypeReference<Map<String,Object>>(){};
    Mono<Map<String,Object>> mono = responseSpec.bodyToMono(typeReference);
    Map<String,Object> response = mono.block();
    for( Object key : response.keySet() ) {
      Object value = response.get(key);
      LoggerFactory.getLogger(getClass()).warn(key+":"+value);
    }
  }
  
  public static void main(String[] args) 
  throws Exception {
    SpringApplication.run(WebClientTest.class, args);
  }
}

有什么想法吗?

默认情况下 spring 引导作为 Web 应用程序或响应式应用程序启动,具体取决于类路径中的库。

但是您也可以通过将 WebApplicationType 显式设置为 None

来告诉框架不要启动网络服务器

这里有一个例子:

new SpringApplicationBuilder(MainApplication.class)
  .web(WebApplicationType.NONE)
  .run(args);

或者您可以在应用程序属性中设置:

spring.main.web-application-type=none

您可以在这里阅读更多相关信息:

17.1.5. Create a Non-web Application

Spring Boot no web server