如何在 Vert.x 中实现自定义异步操作?

How can I implement custom asynchronous operation in Vert.x?

我是 Vert.x 的新手。

例如,JDBCClient有非阻塞方法

JDBCClient.getConnection(Handler<AsyncResult<SQLConnection>> handler)

我调用的时候,真的是异步的

jdbcClient.getConnection(result -> { /* this code will execute asynchonous */})

但是如何使用非阻塞方法实现我自己的组件?

当我写这个例子时,它看起来并不异步。它只会执行方法体,然后调用传递的 lambda。

 class MyComponent { 
   public void getSomething(Handler<AsyncResult<String>> handler) {
       String result = someHeavyMethodInThisThread();
       handler.handle(Future.succeededFuture(result));
   }
 }
 /* later */

 /* this code will be blocking, right? */
 myComponent.getSomething(res -> { /* ... */ })

也许有办法告诉 Vert.x 我的方法应该是异步的?一些注释或其他东西?

您的代码没有问题,您的代码风格通常是异步的,因为当您执行 IO 操作或调用 vert.x API 时,异步操作将使您脱离当前线程(事件循环)。

在您的情况下,您正在执行 CPU 绑定代码,因此它不会表现得像异步一样,正如您所说,只会调用 lambda。如果你仍然想让它异步,你总是可以用 runOnContext 包装你的代码,这将在事件循环的下一次迭代中将它排入 运行 队列,例如:

class MyComponent { 
  public void getSomething(Handler<AsyncResult<String>> handler) {
    vertx.runOnContext(v -> {
      String result = someHeavyMethodInThisThread();
      handler.handle(Future.succeededFuture(result));
    });
  }
}