rest - 如何使用 Vert.x 实现非阻塞 REST Web 服务

标签 rest nonblocking vert.x

我是 Vert.x 的新手。我遵循了 Vert.x 文档和一些教程。但是我很困惑使用 Vert.x 实现非阻塞 REST Web 服务的正确方法是什么。我找到这篇文章Develop Non-Blocking Web Applications in Java其中包含使用 Vert.x 实现非阻塞 Web 应用程序的示例。

此代码块包含向另一个垂直行业发送消息("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() 但他也必须等到前一个用户完成任务。那么如何避免此类问题。谢谢。

最佳答案

请查看此博客系列:

  • first post描述了如何使用 Maven 构建 vert.x 应用程序并执行单元测试。
  • second post描述了如何使该应用程序变得可配置。
  • third post推出了vertx-web,并开发了一个小型集合管理应用程序。此应用程序提供由 HTML/JavaScript 前端使用的 REST API。
  • fourth post介绍了如何运行集成测试以确保应用程序的行为。
  • fifth post介绍了如何使用 vertx-jdbc-client 与 JDBC 数据库交互。
  • 当前的最后一篇文章介绍了如何与 MongoDB 交互。

关于rest - 如何使用 Vert.x 实现非阻塞 REST Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922003/

相关文章:

c# - 从 stdin 非阻塞读取一个字节

java - VertX 和 Log4j 无法获取配置

web-services - API 设计中的功能结构

java - REST 二进制数据

c - 启用非阻塞套接字

java - 非阻塞ServerSocketChannel

java - Vertx 中查询参数的默认值

java - Vert.x 自动缩放 - vert.x 部署多个 verticle

rest - Goroutine 已经根据请求在 Go Web 服务器中启动,但客户端断开连接,Web 服务器是否可以关闭该特定的 goroutine?

android - Android 上的 Soap 与 Rest