【问题标题】:The grammar in Vertx HttpServerRequestVertx HttpServerRequest 中的语法
【发布时间】:2020-08-15 22:31:54
【问题描述】:

我是Java新手,最近在学习Vertx,看不懂下面的代码是怎么工作的:

@Override
public void start() {
    vertx.createHttpServer()
        .requestHandler(req -> req.response()
          .end("hello"))
        .listen(8080);
}

我的问题是:为什么参数req不需要声明类型,这个req是从哪里来的?

【问题讨论】:

    标签: java vert.x vertx-httpclient


    【解决方案1】:

    让我们把它分成几块。

    创建 HTTP 服务器

    使用我们的 Vertx 实例创建实例 HttpSever

    HttpServer httpServer = vertx.createHttpServer();
    

    定义请求处理程序

    现在,对于我们的HttpServer,我们可以为传入请求定义处理程序。

    我们可以使用HttpServer#requestHandler(Handler<HttpServerRequest> handler) [1]。此方法采用Handler<HttpRequest> 的实例。

    因此,我们可以如下定义Handler<HttpServerRequest> 的实例:

    private static class MyRequestHandler implements Handler<HttpServerRequest> {
    
        @Override
        public void handle(HttpServerRequest req) {
            req.response().end("Hello");
        }
    }
    

    这个处理程序只会为每个传入的请求打印"Hello"

    现在我们可以将MyReqesutHandler 的实例与我们的httpServer 实例关联起来。

    httpServer.requestHandler(new MyRequestHandler())
    

    并在端口8080上启动HTTP服务器

    httpServer.listen(8080);
    

    使用 lambda 重构

    请注意,Handler 是一个所谓的函数式接口 [2],而不是定义整个类,我们可以将 lambda 函数 [3] 直接传递给 httpServer.requestHandler()

    我们可以避免大量样板代码。

    所以通过使用 lambda 我们不需要定义整个类,这样做就足够了:

    httpServer.requestHandler(req -> req.response().end("Hello"));
    

    现在因为 JAVA 编译器知道 httpServer.requestHandler() 接受 Handler&lt;HttpServerRequest&gt; 的实例,它可以在编译类型中推断 req 的类型,只需查看方法声明。

    使用 Fluent API 重构

    随着 vert.x 推广 Fluet API [4],我们可以在不需要中间变量的情况下链接方法。

    vertx.createHttpServer()
          .requestHandler(req -> req.response().end("hello"))
          .listen(8080);
    

    我强烈建议您查看 Java lambda 教程并从中获得好感,因为它们几乎不仅在 Vert.x 中使用,而且在 Java 世界中无处不在。

    玩得开心!


    [1]https://vertx.io/docs/apidocs/io/vertx/core/http/HttpServer.html#requestHandler-io.vertx.core.Handler-

    [2]https://www.baeldung.com/java-8-functional-interfaces

    [3]https://www.geeksforgeeks.org/lambda-expressions-java-8/

    [4]https://en.wikipedia.org/wiki/Fluent_interface

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-06
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      相关资源
      最近更新 更多