首页 > 解决方案 > 在 Vert.x 中,REST 端点是否应该返回 Future还是T?

问题描述

我很难找到正确返回类型的文档。

例如,如果我有一个 REST 端点,它查找并返回一个字符串,该端点的返回类型应该是Future<String>orString吗?此外,这会对事件循环产生什么影响(即返回StringFuture<String>导致更多阻塞)?

谢谢!

标签: javarestfuturevert.x

解决方案


如果您在https://vertx.io/get-started查看快速入门的第 (2) 部分,您会看到我在下面粘贴的代码块(我添加了一些编号的注释):

// Mount the handler for all incoming requests at every path and HTTP method
router
  .route()  // (1)
  .handler(context -> {  // (2)
    // Get the address of the request
    String address = context.request().connection().remoteAddress().toString();
    // Get the query parameter "name"
    MultiMap queryParams = context.queryParams();
    String name = queryParams.contains("name") ? queryParams.get("name") : "unknown";
    // Write a json response
    context.json(  // (3)
      new JsonObject()
        .put("name", name)
        .put("address", address)
        .put("message", "Hello " + name + " connected from " + address)
    );
  });

这是做什么的:

  1. 注册一个Handler(基本上是一个回调),它将为路由器收到的每个请求调用。
  2. 处理程序将使用 a 调用RoutingContext,其中包含对HttpServerRequest表示当前请求的对象的引用,以及HttpServerResponse表示响应的对象。后者允许您控制发送回客户端的响应(即标头、正文等)。
  3. context.json()是编写 JSON 格式响应有效负载的便捷方法 - 正文将被正确格式化,内容类型标头将被设置等。

从根本上说,.json()正在做的是:

  final JsonObject myJson = ...;
  
  final Buffer myJsonBuffer = Json.encodeToBuffer(myJson);

  context.response()
      .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
      .write(myJsonBuffer);

最后三行是响应实际发送回客户端的方式。

如需更详细的解释,请在此处查看有关响应的 Vert.x Web 文档。


推荐阅读