【问题标题】:How to implement non blocking REST web service using Vert.x如何使用 Vert.x 实现非阻塞 REST Web 服务
【发布时间】: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


    【解决方案1】:

    请看这个博客系列:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-12
      • 2021-01-17
      • 2017-08-04
      • 2018-06-14
      • 2019-05-31
      • 2017-11-12
      • 2011-10-03
      • 2021-01-12
      相关资源
      最近更新 更多