Undertow + CompletableFuture / RxJava

时间:2017-02-15 09:19:55

标签: java rx-java undertow completable-future

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();
    }
}

使用underow是hello world应用程序。 有人可以提供Undertow + CompletableFuture或RxJava的示例吗?我搜索过但没有成功。

1 个答案:

答案 0 :(得分:2)

以下是RxJava 2的下载世界:

public static void main(final String[] args) {
    Observable<HttpServerExchange> exchangeObservable = Observable.create(observableEmitter -> {
        Undertow server = Undertow.builder()
                .addHttpListener(8080, "localhost")
                .setHandler(new HttpHandler() {
                    @Override
                    public void handleRequest(final HttpServerExchange exchange) throws Exception {
                        observableEmitter.onNext(exchange);
                    }
                }).build();
        server.start();
        observableEmitter.setCancellable(() -> server.stop());
    });

    exchangeObservable.subscribe(exchange -> {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
        exchange.getResponseSender().send("Hello World");
    });
}

这只是一个简单的例子,hello world Undertow + RxJava,没有考虑其他内容的线程管理。我使用Observable.create()打包HttpHandler,并将其回调到Observable。此Observable表示您将使用的传入请求流(exchangeObservable.subscribe()部分)来处理请求。

RxJava只会将语法从回调更改为可观察模式,并提供一组良好的运算符来处理它们:http://reactivex.io/documentation/operators.html