java - 在 Vert.x 中,REST 端点是否应该返回 Future还是T?
问题描述
我很难找到正确返回类型的文档。
例如,如果我有一个 REST 端点,它查找并返回一个字符串,该端点的返回类型应该是Future<String>
orString
吗?此外,这会对事件循环产生什么影响(即返回String
会Future<String>
导致更多阻塞)?
谢谢!
解决方案
如果您在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)
);
});
这是做什么的:
- 注册一个
Handler
(基本上是一个回调),它将为路由器收到的每个请求调用。 - 处理程序将使用 a 调用
RoutingContext
,其中包含对HttpServerRequest
表示当前请求的对象的引用,以及HttpServerResponse
表示响应的对象。后者允许您控制发送回客户端的响应(即标头、正文等)。 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 文档。
推荐阅读
- r - 如何使预测区间覆盖没有数据点的区域
- javascript - 来自 selenium webdriver 的窗口对象是空数组
- jmeter - Jmeter 吞吐量整形计时器发送更多请求然后需要
- javascript - Cookie 在 Microsoft Edge 中设置后消失
- inno-setup - 在 Inno Setup 窗口中打开外部程序
- angular - 日期更改事件未以角度触发
- hyperledger-fabric - 如何使用节点 sdk 将对等点动态添加到现有的超级账本结构网络?
- python - 如何在python中拆分长度列表
- android - Android Studio gradle 问题中的 Flutter 项目
- javascript - 如何在控制器的rails flash错误消息中添加link_to模式窗口?