我正在使用 Undertow 创建一个简单的应用程序。
public class App {
public static void main(String[] args) {
Undertow server = Undertow.builder().addListener(8080, "localhost")
.setHandler(new HttpHandler() {
public void handleRequest(HttpServerExchange exchange) throws Exception {
Thread.sleep(5000);
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello World");
}
}).build();
server.start();
}
}
我打开浏览器选项卡localhost:8080
我打开第二个
选项卡也打开localhost:8080
这次第一个选项卡将等待 5 秒,第二个选项卡将等待 10 秒
为什么会这样呢?
The HttpHandler在 I/O 线程中执行。如中所述文档 http://undertow.io/documentation/core/listeners.html:
IO 线程执行非阻塞任务,并且永远不应该执行阻塞操作因为它们负责多个连接,所以当操作阻塞时其他连接基本上会挂起。每个 CPU 核心一个 IO 线程是合理的默认值。
The 请求生命周期文档 https://undertow.io/undertow-docs/undertow-docs-2.1.0/index.html#undertow-request-lifecycle讨论如何将请求分派给工作线程:
import io.undertow.Undertow;
import io.undertow.server.*;
import io.undertow.util.Headers;
public class Under {
public static void main(String[] args) {
Undertow server = Undertow.builder()
.addListener(8080, "localhost")
.setHandler(new HttpHandler() {
public void handleRequest(HttpServerExchange exchange)
throws Exception {
if (exchange.isInIoThread()) {
exchange.dispatch(this);
return;
}
exchange.getResponseHeaders()
.put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender()
.send("Hello World");
}
})
.build();
server.start();
}
}
我注意到,每个请求不一定会获得一个工作线程 - 当我在标头上设置断点时,每个客户端大约会获得一个线程。 Undertow 和底层都有间隙XNIO 文档 https://docs.jboss.org/author/display/XNIO/Workers所以我不确定目的是什么。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)