如何使用Vert.x实现非阻塞RESTWeb服务

如何使用Vert.x实现非阻塞RESTWeb服务,rest,nonblocking,vert.x,Rest,Nonblocking,Vert.x,我是Vert.x的新手。我遵循了Vert.x文档和一些教程,但我不知道使用Vert.x实现非阻塞RESTWeb服务的正确方法是什么。我发现了这篇文章,其中包含了一个使用Vert.x实现非阻塞Web应用程序的示例 此代码块包含向另一个垂直(“todoService”:TodoServiceVerticle)发送消息 JsonObject命令=新建JsonObject(); putString(“action”、“findOne”)。 putNumber(“id”,Long.valueOf(requ

我是Vert.x的新手。我遵循了Vert.x文档和一些教程,但我不知道使用Vert.x实现非阻塞RESTWeb服务的正确方法是什么。我发现了这篇文章,其中包含了一个使用Vert.x实现非阻塞Web应用程序的示例

此代码块包含向另一个垂直(“todoService”:TodoServiceVerticle)发送消息

JsonObject命令=新建JsonObject();
putString(“action”、“findOne”)。
putNumber(“id”,Long.valueOf(request.params().get(“id”));
字符串地址=“todoService”;
vertx.eventBus().send(地址、命令、消息)->{
JsonObject item=message.body();
字符串有效负载=item.encode();
请求.响应()
.putHeader(“内容类型”、“应用程序/json”)
(完);
});
这是“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);
    }
}
公共类TodoServiceVerticle扩展了Verticle{
/**在启动时初始化垂直*/
@重写公共void start(){
//初始化垂直面
registerHandler(“todoService”,this::onMessage);
}
私有void onMessage(消息消息){
JsonObject命令=message.body();
//本例中仅支持“findOne”
断言(“findOne”.equals(command.getString(“action”));
Long id=command.getLong(“id”);
Todo项=findOneById(id);
JsonObject有效载荷=toJson(项);
消息回复(有效载荷);
}
}
在本例中,服务器在一个线程上运行。所有http请求都到达同一个线程。TodoServiceVerticle在另一个线程中运行


现在我的问题是,如果TodoServiceVerticle.onMessage()函数包含耗时的任务(例如:-DB操作,读取大文件,…),它将阻止进程。同时假设另一个用户调用TodoServiceVerticle.onMessage()但他也必须等到前一个用户完成任务。因此如何避免此类问题。谢谢。

请查看此博客系列:

  • 本文描述了如何使用Maven构建vert.x应用程序并执行单元测试
  • 描述了如何配置此应用程序
  • 引入了VertXWeb,并开发了一个小型的收藏管理应用程序。此应用程序提供HTML/JavaScript前端使用的RESTAPI
  • 介绍了如何运行集成测试以确保应用程序的行为
  • 介绍了如何使用VertxJDBC客户机与JDBC数据库交互
  • 最近的一篇文章介绍了如何与MongoDB交互
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);
    }
}