【发布时间】:2018-11-26 18:50:33
【问题描述】:
我正在使用带有 Netty 的 Spring Webflux (2.0.3.RELEASE) 并尝试了解服务器和 Web 客户端如何使用线程。我用 WebClient 编写了一些带有 http 调用链的代码。我怀疑所有呼叫都是非阻塞的,但我不明白为什么只有一个请求通过了整个链。这是下面的代码和日志输出:
public class DemoApplication {
private WebClient webclient = WebClient.create("http://localhost:8080/");
public static void main(String[] args) throws Exception {
new DemoApplication().startServer();
}
public void startServer() throws Exception {
RouterFunction<ServerResponse> route = routingFunction();
HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
HttpServer server = HttpServer.create("127.0.0.1", 8080);
server.newHandler(adapter).block();
Thread.sleep(1000000);
}
public RouterFunction<ServerResponse> routingFunction() throws Exception {
return route(path("/1"), req -> ok().body(fromPublisher(get1(), String.class)))
.andRoute(path("/2"), req -> ok().body(fromPublisher(get2(), String.class)))
.andRoute(path("/3"), req -> ok().body(fromPublisher(get3(), String.class)));
}
public Mono<String> get1() {
System.out.println("---------REQUEST---------");
System.out.println("1: " + Thread.currentThread());
return webclient.get().uri("2").retrieve().bodyToMono(String.class);
}
public Mono<String> get2() {
System.out.println("2: " + Thread.currentThread());
return webclient.get().uri("3").retrieve().bodyToMono(String.class);
}
public Mono<String> get3() {
System.out.println("3: " + Thread.currentThread());
try {
Thread.sleep(1250000); // simulate thread somehow got blocked
} catch (InterruptedException e) {
}
return Mono.just("test");
}
}
我对 localhost:8080/1 进行了 4 次调用并得到以下输出。只有一个请求设法到达第三种方法。我预计当一个线程被阻塞时,其他三个将能够处理其他请求,但他们没有。整个线程池由 4 个线程组成(与内核数相同)。
---------REQUEST---------
1: Thread[reactor-http-nio-2,5,main]
2: Thread[reactor-http-nio-4,5,main]
3: Thread[reactor-http-nio-2,5,main]
---------REQUEST---------
1: Thread[reactor-http-nio-3,5,main]
2: Thread[reactor-http-nio-1,5,main]
---------REQUEST---------
1: Thread[reactor-http-nio-3,5,main]
2: Thread[reactor-http-nio-1,5,main]
---------REQUEST---------
1: Thread[reactor-http-nio-3,5,main]
2: Thread[reactor-http-nio-1,5,main]
您能解释一下这种行为吗?
--------编辑-------
说明: https://groups.google.com/forum/#!topic/netty/1kAS-FJWGRE
【问题讨论】:
标签: spring-webflux project-reactor reactive