Imr*_*ran 5 java lambda vert.x
这是我的代码的简化版本:
public void pairing() {
WebClient web = WebClient.create(vertx);
String url = "/request";
JsonObject obj = new JsonObject();
web
.post(6660, "localhost", url)
.sendJsonObject(obj, response -> {
JsonObject pairing = response.result().body().toJsonObject(); // what I want to return
}
}
Run Code Online (Sandbox Code Playgroud)
这会向localhost:6660/request发出POST请求,并创建一个名为pairing的新JsonObject,用于存储对该请求的响应.我可以处理请求的lambda表达式内部的配对,但理想情况下,我可以将JsonObject返回到调用pairing()并从那里处理它的方法.
我试过这个:
public JsonObject pairing() {
JsonObject pairing = new JsonObject();
WebClient web = WebClient.create(vertx);
String url = "/request";
JsonObject obj = new JsonObject();
web
.post(6660, "localhost", url)
.sendJsonObject(obj, response -> {
pairing = response.result().body().toJsonObject();
}
return pairing;
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用,因为我得到"配对必须是最终的或有效的最终"错误.有没有什么方法可以从这个方法返回"配对",以便我可以在我的程序中的其他位置访问它?或者我可能以错误的方式接近这个?
使用期货:
public Future<JsonObject> pairing() {
Future<JsonObject> future = Future.future();
WebClient web = WebClient.create(vertx);
String url = "/request";
JsonObject obj = new JsonObject();
web
.post(6660, "localhost", url)
.sendJsonObject(obj, response -> {
future.complete(response.result().body().toJsonObject());
}
return future;
}
Run Code Online (Sandbox Code Playgroud)
现在调用这个函数:
pairing().setHandler(r -> {
r.result // This is your JSON object
});
Run Code Online (Sandbox Code Playgroud)
WebClient将异步执行.您正在尝试的是同步,这是使用WebClient无法实现的,同步调用也将是vert.x中的阻塞调用.这也是黄金法则,不要阻止事件循环.
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |