简体   繁体   English

如何在 vert.x 中执行断开连接的阻塞任务?

[英]How to execute a disconnected blocking task in vert.x?

I'd like use Vert.x to implement an asynchronous job executor.我想使用 Vert.x 来实现一个异步作业执行器。

In other words:换句话说:

  1. http request arrives http 请求到达
  2. new thread is spawn to execute a long running blocking task产生新线程以执行长时间运行的阻塞任务
  3. respond to the client (accepted request)响应客户端(接受请求)
  4. when the blocking task is completed, a http request is performed to inform the caller.当阻塞任务完成时,执行http请求通知调用者。

Is Vert.x the right choice for such logic? Vert.x 是这种逻辑的正确选择吗?

Can you provide hints on how to implement this?您能否提供有关如何实现此功能的提示?

Vert.x main benefit is high concurrency. Vert.x 的主要好处是高并发。 By their nature long running tasks are not concurrent, so you won't gain much benefit from using Vert.x就其性质而言,长时间运行的任务不是并发的,因此您不会从使用 Vert.x 中获得太多好处

Anyway, Step 1 is your standard router.无论如何,第 1 步是您的标准路由器。

final Router router = Router.router(this.vertx);
router.post("/jobs").handler(ctx -> {
   vertx.eventBus().send("jobsAddress", "some job data?");
   ...
});

Step 2 would be to launch worker verticles:第 2 步是启动 worker verticles:

// In your main class
vertx.deployVerticle("your.worker.Verticle", new DeploymentOptions()
        .setWorkerPoolSize(20)
        .setWorker(true));

// In Worker class:
public class JobWorkerVerticle extends AbstractVerticle {

   @Override
   public void start() throws Exception {      
      vertx.eventBus().consumer("jobsAddress").handler(ctx -> {
          // Start your job
      });
   }
   ...
 }

Step 3 is again just standard router.第 3 步再次只是标准路由器。

    router.post("/jobs").handler(ctx -> {
        ctx.response().setStatusCode(204).end();
    });

Finally, Step 4 is another route, GET this time:最后,第 4 步是另一条路线,这次 GET:

router.get("/jobs/:id").handler(ctx -> {
   // Check if the job is completed or not yet
});

As an alternative, you can use WebSockets, and then respond with two types of messages: one for accepted job, and one for completed job.作为替代方案,您可以使用 WebSockets,然后使用两种类型的消息进行响应:一种用于已接受的作业,另一种用于已完成的作业。

The examples are with Vert.x 3.8, so if you're using Vert.x 4+, they'll probably have to be adapted a bit.这些示例使用 Vert.x 3.8,因此如果您使用的是 Vert.x 4+,则可能需要对其进行一些调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM