加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Undertow如何做非阻塞IO?

发布时间:2020-12-14 05:11:36 所属栏目:Java 来源:网络整理
导读:我使用undertow创建一个简单的应用程序. public class App { public static void main(String[] args) { Undertow server = Undertow.builder().addListener(8080,"localhost") .setHandler(new HttpHandler() { public void handleRequest(HttpServerExchan
我使用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都有差距,所以我不知道是什么意思.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读