java – Undertow如何做非阻塞IO?

前端之家收集整理的这篇文章主要介绍了java – Undertow如何做非阻塞IO?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用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();
    }
}

i open a brower tag entry the localhost:8080 and open second
tab entry localhost:8080

这次第一个标签将等待5秒钟,第二个等待10秒钟

为什么会这样?

解决方法

HttpHandler正在I / O线程中执行.如 the documentation所述:

IO threads perform non blocking tasks,and should never perform blocking operations because they are responsible for multiple connections,so while the operation is blocking other connections will essentially hang. One IO thread per cpu core is a reasonable default.

request lifecycle docs讨论如何向工作线程发送请求:

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 docs都有差距,所以我不知道是什么意思.

原文链接:https://www.f2er.com/java/123169.html

猜你在找的Java相关文章