gpt4 book ai didi

java - Vert.x 请求处理程序和阻塞数据库查询

转载 作者:行者123 更新时间:2023-12-02 09:43:03 24 4
gpt4 key购买 nike

如何在 vert.x 中正确翻译这段代码?

通常,在 spring 中或在带有模板引擎的简单 sevlet 中输出 html 响应,我会这样做

function test(request, response) {
templatecontext tc = getContext();

init conditions

if (condition1) {
retrieve data from db ({
asyncresult -> {
tc.put("data1", data1)
})
} else if (condition2) {
other code

if (condition 2.1) {
retrieve data from db ({
asyncresult -> {
tc.put("data2", data2)
})
}
}

get other data from db and put in context
template.eval("templatefile", tc)
write to response
}

问题是,从数据库检索数据是异步结果的处理程序,因此我不能同意使用 data1 或 data2 进行模板评估,因为检索异步不会陷入回调 hell 。

我还没有真正理解rxjava2,但我感觉我正试图用勺子杀死一颗 bean 。

最佳答案

您可以使用futurescomposition 。请参阅 vertx-examples 中的 ComposeExample repo 协议(protocol):

public class ComposeExample extends AbstractVerticle {    

@Override
public void start() throws Exception {
Future<String> future = anAsyncAction();
future.compose(this::anotherAsyncAction)
.setHandler(ar -> {
if (ar.failed()) {
System.out.println("Something bad happened");
ar.cause().printStackTrace();
} else {
System.out.println("Result: " + ar.result());
}
});
}

private Future<String> anAsyncAction() {
Future<String> future = Future.future();
// mimic something that take times
vertx.setTimer(100, l -> future.complete("world"));
return future;
}

private Future<String> anotherAsyncAction(String name) {
Future<String> future = Future.future();
// mimic something that take times
vertx.setTimer(100, l -> future.complete("hello " + name));
return future;
}
}

关于java - Vert.x 请求处理程序和阻塞数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56903040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com