问题描述
我是Vert.x的新手.
I am newbie in Vert.x.
例如, JDBCClient
具有非阻塞方法
JDBCClient.getConnection(Handler<AsyncResult<SQLConnection>> handler)
当我调用它时,它实际上是异步的.
When I call it, it is really asynchronous.
jdbcClient.getConnection(result -> { /* this code will execute asynchonous */})
但是如何使用非阻塞方法实现自己的组件?
But how can I implement my own component with non-blocking methods?
例如,当我写这篇文章时,它看起来并不异步.它只会执行方法主体,然后调用传递的lambda.
When I write for example this, it doesnt looks asynchronous. It just will execute method body and then will call passed 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我的方法应该是异步的?一些注释或其他内容?
Maybe there is way to tell Vert.x that my method should be asynchronous? Some annotation or something else?
推荐答案
代码没有问题,代码风格通常是异步的,因为执行IO操作或调用vert.x API的那一刻是异步的操作将使您脱离当前线程(事件循环).
There is nothing wrong with your code, your code style, normally will be async because the moment you perform a IO operation or call a vert.x API a async operation will detach you from the current thread (event loop).
在您的情况下,您正在执行受CPU约束的代码,因此它不会表现为异步,并且正如您所说的那样,将仅调用lambda.尽管如此,如果您仍要使其异步,则始终可以使用 runOnContext
包装代码,这将使其排队在事件循环的下一次迭代中运行,例如:
In your case you're doing CPU bound code so it does not behave as async and as you stated will just call the lambda. If you want nevertheless make it async you can always wrap your code with runOnContext
and that will enqueue it to be run on the next iteration of the event loop, e.g.:
class MyComponent {
public void getSomething(Handler<AsyncResult<String>> handler) {
vertx.runOnContext(v -> {
String result = someHeavyMethodInThisThread();
handler.handle(Future.succeededFuture(result));
});
}
}
这篇关于如何在Vert.x中实现自定义异步操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!