这是在the vertx documentation on thread safety的上下文中,它表示:
大多数Vert.x对象可以从不同线程安全访问。但是,当从创建它们的相同上下文访问它们时,性能会得到优化。
考虑到这一点,如果我们使用vertx-guice注入创建vertx对象的服务(例如Web客户端),它将与创建的Verticle在同一Vert.X上下文中,因此效率很高可能吗?
示例代码如下:
public class FooService {
private final HttpClient httpClient;
@Inject
public FooService(Vertx vertx) {
httpClient = vertx.createHttpClient();
}
public void queryGoogle(Handler<AsyncResult<String>> resultHandler ) {
httpClient.getAbs("http://www.google.co.uk/", response -> {
if (response.statusCode() == 200) {
response.bodyHandler(body -> resultHandler.handle(Future.succeededFuture(body.toString())));
} else {
resultHandler.handle(Future.failedFuture("Failed to query google"));
}
})
.end();
}
}
public class FooVerticle extends AbstractVerticle {
private final FooService fooService;
@Inject
public FooVerticle(FooService fooService) {
this.fooService = fooService;
}
@Override
public void start(Future<Void> startFuture) throws Exception {
Future<String> queryFuture = Future.future();
queryFuture.setHandler(result -> {
System.out.println("Received result" + result);
startFuture.handle(Future.succeededFuture());
});
fooService.queryGoogle(queryFuture);
}
}