如何使用 Vert.x 从 EventBus 中获取结果
How to get the result out of EventBus using Vert.x
伙计们!
在使用Vert.x时,我发现在与其他 Verticle 通信时无法从 EventBus 中获取结果。
class Result<T> {
public T value;
public String message;
// ...
}
private Result<Integer> someMethod() {
try {
var json = new JsonObject();
vertx.eventBus().<JsonObject>send(Service.EVENT_BUS_ADDRESS, json, ar -> {
if (ar.succeeded()) {
var result = new Result<List>(ar.result().body());
if (result.isSuccessful()) {
Result.succeed(result);
} else {
Result.fail(result.message);
}
} else {
Result.fail("Remote server error");
}
});
} catch (Exception e) {
e.printStackTrace();
return Result.fail(e.getMessage());
}
return // how can I return the result in EventBus???
}
那么我怎样才能从 Async
块和 return 块中获取值呢?
您不应该 return 结果,而是通知处理程序
以下代码假定您的Result.succeeed
或Result.fail
方法return
Result
的实例
private void someMethod(Handler<Result> resultHandler) {
...
vertx.eventBus().<JsonObject>send(Service.EVENT_BUS_ADDRESS, json, ar -> {
if (ar.succeeded()) {
var result = new Result<List>(ar.result().body());
if (result.isSuccessful()) {
resultHandler.handle(Result.succeed(result));
} else {
resultHandler.handle(Result.fail(result.message));
}
} else {
resultHandler.handle(Result.fail("Remote server error"));
}
...
}
伙计们!
在使用Vert.x时,我发现在与其他 Verticle 通信时无法从 EventBus 中获取结果。
class Result<T> {
public T value;
public String message;
// ...
}
private Result<Integer> someMethod() {
try {
var json = new JsonObject();
vertx.eventBus().<JsonObject>send(Service.EVENT_BUS_ADDRESS, json, ar -> {
if (ar.succeeded()) {
var result = new Result<List>(ar.result().body());
if (result.isSuccessful()) {
Result.succeed(result);
} else {
Result.fail(result.message);
}
} else {
Result.fail("Remote server error");
}
});
} catch (Exception e) {
e.printStackTrace();
return Result.fail(e.getMessage());
}
return // how can I return the result in EventBus???
}
那么我怎样才能从 Async
块和 return 块中获取值呢?
您不应该 return 结果,而是通知处理程序
以下代码假定您的Result.succeeed
或Result.fail
方法return
Result
private void someMethod(Handler<Result> resultHandler) {
...
vertx.eventBus().<JsonObject>send(Service.EVENT_BUS_ADDRESS, json, ar -> {
if (ar.succeeded()) {
var result = new Result<List>(ar.result().body());
if (result.isSuccessful()) {
resultHandler.handle(Result.succeed(result));
} else {
resultHandler.handle(Result.fail(result.message));
}
} else {
resultHandler.handle(Result.fail("Remote server error"));
}
...
}