Java開發的高性能無阻塞Web服務器:Undertow
Undertow用Java寫的一個靈活的高性能web服務器,同時提供阻塞和非阻塞的基于NIO的API。
Undertow 提供一個基礎的架構用來構建 Web 服務器,允許您通過合并小單用途處理器來構建一個Web服務器,完全兼容 Java EE Servlet 3.1 和低級非堵塞的處理器。
Undertow 是紅帽公司的開源產品,是 Wildfly 默認的 Web 服務器。
它擁有的特性:
- 輕量級
-
Undertow極其輕量級,Undertow核心jar在1MB以下。它是在運行時用不到4Mb的堆空間(heap space),一個簡單的嵌入式服務器。
- HTTP Upgrade支持
-
Support for HTTP upgrade, to allow multiple protocols to be multiplexed over the HTTP port。
- Web Socket 支持
-
Undertow提供 Web Sockets的完整支持,包括JSR-356支持的全面支持。
- Servlet 3.1
-
Undertow提供 Servlet 3.1 支持,including support for embedded servlet. It is also possible to mix both Servlets and native undertow non-blocking handlers in the same deployment.
- 可嵌入
-
Undertow can be embedded in an application or run standalone with just a few lines of code.
- 靈活
-
An Undertow server is configured by chaining handlers together. It is possible to add as much or as little functionality as you need, so you don’t pay for what you are not using.
下面是一個使用異步IO實現的一個簡單的Hello World服務器:
public class HelloWorldServer { public static void main(final String[] args) { Undertow server = Undertow.builder() .addHttpListener(8080, "localhost") .setHandler(new HttpHandler() { @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseSender().send("Hello World"); } }).build(); server.start(); } }