I'm currently tying to implement morphia (mongoDb's official Java ORM) with Vert.x 3 but it looks like all the queries and calls are done synchronously and can block the eventloop of Vert.x 3
我目前正致力于用Vert实现morphia (mongoDb的官方Java ORM)。但是看起来所有的查询和调用都是同步完成的,可以阻塞Vert的eventloop。x 3
How do turn this query into a non-blocking set of code.
如何将该查询转换为一组非阻塞的代码。
DBObject query = BasicDBObjectBuilder.start()
.add("albums",
new BasicDBObject("$elemMatch",
new BasicDBObject("$and", new BasicDBObject[] {
new BasicDBObject("albumId", albumDto.getAlbumId()),
new BasicDBObject("album",
new BasicDBObject("$exists", false))
})))
.get();
Query<Artist> findQuery = datastore.createQuery(Artist.class, query);
Artist result = findQuery.get();
1 个解决方案
#1
2
If you want to use synchronous code in Vert.x you have 2 options:
如果您想在Vert中使用同步代码。你有两个选择:
- Use a worker verticle
- 使用一个工人垂直
- Wrap your call in a
executeBlocking
closure - 在执行阻塞闭包中包装您的调用
A worker verticle is always executed with a thread from the worker pool. However if you want to mix both async and sync you probably want to use the second option. You can read all about executeBlocking
here. Given your example it would be something like:
工作线程垂直总是使用来自工作线程池的线程执行。但是,如果您想同时使用异步和同步,您可能需要使用第二个选项。您可以在这里阅读有关executeblock的所有内容。以你的例子来说,可能是这样的:
DBObject query = ... // your definition is probably non blocking
vertx.executeBlocking(future -> {
// Call blocking API that takes a significant amount of time to return
Artist result = findQuery.get();
future.complete(result);
}, res -> {
System.out.println("The artist is: " + res.result());
});
#1
2
If you want to use synchronous code in Vert.x you have 2 options:
如果您想在Vert中使用同步代码。你有两个选择:
- Use a worker verticle
- 使用一个工人垂直
- Wrap your call in a
executeBlocking
closure - 在执行阻塞闭包中包装您的调用
A worker verticle is always executed with a thread from the worker pool. However if you want to mix both async and sync you probably want to use the second option. You can read all about executeBlocking
here. Given your example it would be something like:
工作线程垂直总是使用来自工作线程池的线程执行。但是,如果您想同时使用异步和同步,您可能需要使用第二个选项。您可以在这里阅读有关executeblock的所有内容。以你的例子来说,可能是这样的:
DBObject query = ... // your definition is probably non blocking
vertx.executeBlocking(future -> {
// Call blocking API that takes a significant amount of time to return
Artist result = findQuery.get();
future.complete(result);
}, res -> {
System.out.println("The artist is: " + res.result());
});