当前位置: 首页 > 知识库问答 >
问题:

Spring Boot WebClient:在响应前过早关闭连接

杭曦
2023-03-14
    null

请参见REST API服务器的代码

@RestController
@RequestMapping("/api")
public class UserApi {

    @GetMapping(path = "/test")
    public String test() {
        System.out.println("Test Request Started");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Test Request Ended");

        return "OK";
    }

}

REST客户端的代码

public class RestClient{

    public void restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        String string = restTemplate.getForObject("http://localhost:8080/api/test", String.class);
        System.out.println(string);
    }

    public void webClient() {
         Mono<String> bodyToMono = WebClient.create("http://localhost:8080/")
                .get()
                .uri("/api/test")
                .retrieve()
                .bodyToMono(String.class);
         bodyToMono.subscribe(System.out::println);
    }
}

我从我的Spring Boot Main方法调用这个类为

@SpringBootApplication
public class WebClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebClientApplication.class, args);
        RestClient restClient = new RestClient();
        System.out.println("Testing with Webclient");
        restClient.webClient();
        System.out.println("Testing with RestTemplate");
        restClient.restTemplate();
    }

}
Caused by: reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ Request to GET http://localhost:8080/api/test [DefaultWebClient]
Stack trace:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.0.RELEASE)

2020-05-16 16:32:17.506  INFO 9928 --- [  restartedMain] c.w.server.client.WebClientApplication   : Starting WebClientApplication on DESKTOP-054O660 with PID 9928 (D:\eclipse-jee-2019-09-R-win32-x86_64\workspace\WebClientDemoServer\client\target\classes started by Akshay in D:\eclipse-jee-2019-09-R-win32-x86_64\workspace\WebClientDemoServer\client)
2020-05-16 16:32:17.506  INFO 9928 --- [  restartedMain] c.w.server.client.WebClientApplication   : No active profile set, falling back to default profiles: default
2020-05-16 16:32:17.631  INFO 9928 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-05-16 16:32:17.631  INFO 9928 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-05-16 16:32:19.004 DEBUG 9928 --- [  restartedMain] reactor.netty.tcp.TcpResources           : [http] resources will use the default LoopResources: DefaultLoopResources {prefix=reactor-http, daemon=true, selectCount=4, workerCount=4}
2020-05-16 16:32:19.007 DEBUG 9928 --- [  restartedMain] reactor.netty.tcp.TcpResources           : [http] resources will use the default ConnectionProvider: reactor.netty.resources.PooledConnectionProvider@6eb63cda
2020-05-16 16:32:19.053  INFO 9928 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-05-16 16:32:19.121  INFO 9928 --- [  restartedMain] c.w.server.client.WebClientApplication   : Started WebClientApplication in 2.446 seconds (JVM running for 3.272)
Testing with Webclient
2020-05-16 16:32:20.680 DEBUG 9928 --- [  restartedMain] r.netty.resources.DefaultLoopEpoll       : Default Epoll support : false
2020-05-16 16:32:20.688 DEBUG 9928 --- [  restartedMain] r.netty.resources.DefaultLoopKQueue      : Default KQueue support : false
2020-05-16 16:32:20.893 DEBUG 9928 --- [  restartedMain] r.n.resources.PooledConnectionProvider   : Creating a new client pool [PoolFactory {maxConnections=500, pendingAcquireMaxCount=-1, pendingAcquireTimeout=45000, maxIdleTime=-1, maxLifeTime=-1, metricsEnabled=false}] for [localhost:8080]
Testing with RestTemplate
2020-05-16 16:32:21.369 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df] Created a new pooled channel, now 1 active connections and 0 inactive connections
2020-05-16 16:32:21.440 DEBUG 9928 --- [ctor-http-nio-1] reactor.netty.channel.BootstrapHandlers  : [id: 0x77afe9df] Initialized pipeline DefaultChannelPipeline{(BootstrapHandlers$BootstrapInitializerHandler#0 = reactor.netty.channel.BootstrapHandlers$BootstrapInitializerHandler), (PooledConnectionProvider$PooledConnectionAllocator$PooledConnectionInitializer#0 = reactor.netty.resources.PooledConnectionProvider$PooledConnectionAllocator$PooledConnectionInitializer), (reactor.left.httpCodec = io.netty.handler.codec.http.HttpClientCodec), (reactor.left.decompressor = io.netty.handler.codec.http.HttpContentDecompressor), (reactor.right.reactiveBridge = reactor.netty.channel.ChannelOperationsHandler)}
2020-05-16 16:32:21.457 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080] Registering pool release on close event for channel
2020-05-16 16:32:21.458 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080] Channel connected, now 1 active connections and 0 inactive connections
2020-05-16 16:32:21.459 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080] onStateChange(PooledConnection{channel=[id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080]}, [connected])
2020-05-16 16:32:21.473 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080] onStateChange(GET{uri=/, connection=PooledConnection{channel=[id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080]}}, [configured])
2020-05-16 16:32:21.475 DEBUG 9928 --- [ctor-http-nio-1] r.netty.http.client.HttpClientConnect    : [id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080] Handler is being applied: {uri=http://localhost:8080/api/test, method=GET}
2020-05-16 16:32:21.477 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080] onStateChange(GET{uri=/api/test, connection=PooledConnection{channel=[id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080]}}, [request_prepared])
2020-05-16 16:32:21.517 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080] onStateChange(GET{uri=/api/test, connection=PooledConnection{channel=[id: 0x77afe9df, L:/127.0.0.1:52476 - R:localhost/127.0.0.1:8080]}}, [request_sent])
OK
2020-05-16 16:32:26.476 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df, L:/127.0.0.1:52476 ! R:localhost/127.0.0.1:8080] Channel closed, now 0 active connections and 0 inactive connections
2020-05-16 16:32:26.476 DEBUG 9928 --- [ctor-http-nio-1] r.n.resources.PooledConnectionProvider   : [id: 0x77afe9df, L:/127.0.0.1:52476 ! R:localhost/127.0.0.1:8080] onStateChange(GET{uri=/api/test, connection=PooledConnection{channel=[id: 0x77afe9df, L:/127.0.0.1:52476 ! R:localhost/127.0.0.1:8080]}}, [response_incomplete])
2020-05-16 16:32:26.491  WARN 9928 --- [ctor-http-nio-1] r.netty.http.client.HttpClientConnect    : [id: 0x77afe9df, L:/127.0.0.1:52476 ! R:localhost/127.0.0.1:8080] The connection observed an error

reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response

2020-05-16 16:32:26.491  WARN 9928 --- [ctor-http-nio-1] reactor.netty.channel.FluxReceive        : [id: 0x77afe9df, L:/127.0.0.1:52476 ! R:localhost/127.0.0.1:8080] An exception has been observed post termination

reactor.core.Exceptions$ErrorCallbackNotImplemented: reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
Caused by: reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ Request to GET http://localhost:8080/api/test [DefaultWebClient]
Stack trace:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.0.RELEASE)

2020-05-16 16:36:25.661  INFO 6812 --- [  restartedMain] c.w.s.WebClientDemoServerApplication     : Starting WebClientDemoServerApplication on DESKTOP-054O660 with PID 6812 (D:\eclipse-jee-2019-09-R-win32-x86_64\workspace\WebClientDemoServer\server\target\classes started by Akshay in D:\eclipse-jee-2019-09-R-win32-x86_64\workspace\WebClientDemoServer\server)
2020-05-16 16:36:25.661  INFO 6812 --- [  restartedMain] c.w.s.WebClientDemoServerApplication     : No active profile set, falling back to default profiles: default
2020-05-16 16:36:25.723  INFO 6812 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-05-16 16:36:25.723  INFO 6812 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-05-16 16:36:26.942  INFO 6812 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-05-16 16:36:26.955  INFO 6812 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-05-16 16:36:26.955  INFO 6812 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-05-16 16:36:27.049  INFO 6812 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-05-16 16:36:27.049  INFO 6812 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1326 ms
2020-05-16 16:36:27.283  INFO 6812 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-16 16:36:27.455 DEBUG 6812 --- [  restartedMain] reactor.netty.tcp.TcpResources           : [http] resources will use the default LoopResources: DefaultLoopResources {prefix=reactor-http, daemon=true, selectCount=4, workerCount=4}
2020-05-16 16:36:27.471 DEBUG 6812 --- [  restartedMain] reactor.netty.tcp.TcpResources           : [http] resources will use the default ConnectionProvider: reactor.netty.resources.PooledConnectionProvider@7f6d3bcb
2020-05-16 16:36:27.487  INFO 6812 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-05-16 16:36:27.533  INFO 6812 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-05-16 16:36:27.549  INFO 6812 --- [  restartedMain] c.w.s.WebClientDemoServerApplication     : Started WebClientDemoServerApplication in 2.36 seconds (JVM running for 3.545)
2020-05-16 16:36:39.781  INFO 6812 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-05-16 16:36:39.789  INFO 6812 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-05-16 16:36:39.791  INFO 6812 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms
Test Request Started
Test Request Started
Test Request Ended
Test Request Ended

共有1个答案

管玉堂
2023-03-14

为了以后的读者。我也遇到过类似的问题,我通过将ReactorClientHttpConnector添加到Webclient创建过程中来解决这个问题。

之前:

        this.webClient = WebClient.builder()
            .baseUrl(url)
            .build();

之后:

        this.webClient = WebClient.builder()
            .baseUrl(url)
            .clientConnector(new ReactorClientHttpConnector(HttpClient.newConnection().compress(true)))
            .build();
 类似资料:
  • 问题内容: 我正在尝试进行AJAX调用(通过JQuery),这将启动一个相当长的过程。我希望脚本仅发送一个指示进程已开始的响应,但是JQuery在PHP脚本运行完成之前不会返回响应。 我已经尝试过使用“关闭”标头(如下),以及输出缓冲了。似乎都不起作用。有什么猜想吗?还是我需要在JQuery中做这件事? 问题答案: 以下PHP手册页(包括用户注释)建议了有关如何在不结束PHP脚本的情况下关闭与浏览

  • 问题内容: 背景 我正在客户端使用HTTP流(服务器推送)情况下的响应。尽管服务器可以通过关闭响应来关闭连接,但是客户端也需要这样做。 问题 客户端在一个单独的线程中处理,如下所示: 因此,当我从发起连接的线程进行调用时(重要的信息是它与处理输入的线程不同),该调用将无限期挂起。我什至把它留了一夜,它仍然挂着。即使打电话也无济于事。 有什么建议吗? 问题答案: 在没有可用字节的情况下,如果不更改读

  • NodeJS的socket.io似乎不能作为websocket服务器工作 谢谢你的帮助

  • 问题内容: 他们似乎遇到了类似的问题,但该解决方案对我不起作用。 基本上,每当我尝试启动uWSGI进程时,我总是遇到Nginx 502错误的网关屏幕。按照文档中的说明,我有两个独立的uwsgi进程正在运行。 当我运行websocket uwsgi实例时,得到以下信息: 这告诉我uwsgi实例运行正常。然后我运行我的下一个uwsgi进程,并且那里也没有错误日志… 当我导航到浏览器中的页面时,带有ha

  • 关于HTTP连接关闭,我有两个问题: > 如果一个客户端通过连接发送一个HTTP请求:靠近HTTP服务器,那么在客户端收到响应后,HTTP服务器还是客户端有责任发送TCP FIN? 如果客户端发送了一个格式错误的HTTP请求,而服务器发送了一个400错误的请求,那么最好的做法是通过服务器关闭连接(即使HTTP请求有connection:keep alive),还是保持连接仍然处于活动状态? 提前感

  • 我正在使用创建。jar文件。它位于下 然后,创建一个简单的,如下所示: 构建docker映像: