【发布时间】:2016-06-25 14:57:03
【问题描述】:
我是 Vert.x 的新手。我关注了 Vert.x 文档和一些教程。但我很困惑使用 Vert.x 实现非阻塞 REST Web 服务的正确方法是什么。我找到了这篇文章Develop Non-Blocking Web Applications in Java,其中包含一个使用 Vert.x 实现非阻塞 Web 应用程序的示例。
此代码块包含向另一个 Vertical("todoService":TodoServiceVerticle) 发送消息。
JsonObject command = new JsonObject();
command.putString("action","findOne").
putNumber("id",Long.valueOf(request.params().get("id")));
String address = "todoService";
vertx.eventBus().send(address, command, (Message<JsonObject> message)-> {
JsonObject item = message.body();
String payload = item.encode();
request.response()
.putHeader("content-type", "application/json")
.end(item);
});
这是 "todoService":TodoServiceVerticle 垂直。
public class TodoServiceVerticle extends Verticle{
/** Initializes the verticle at the start-up */
@Override public void start() {
// Initialize the verticle
vertx.eventBus().registerHandler("todoService", this::onMessage);
}
private void onMessage(Message<JsonObject> message) {
JsonObject command = message.body();
// Only "findOne" is supported in this example
assert ("findOne".equals(command.getString("action")));
Long id = command.getLong("id");
Todo item = findOneById(id);
JsonObject payload = toJson(item);
message.reply(payload);
}
}
在这个例子中,服务器运行在一个线程上。所有的 http 请求都到达同一个线程。TodoServiceVerticle运行在不同的线程上。
现在我的问题是如果 TodoServiceVerticle.onMessage() 函数包含耗时的任务(例如:- 数据库操作,读取大文件,...),它将阻塞进程。假设同时另一个用户调用 TodoServiceVerticle.onMessage() 但他也必须等到前一个用户完成任务。所以如何避免这种问题。谢谢。
【问题讨论】:
标签: rest nonblocking vert.x