簡體   English   中英

Vert.x請求處理程序並阻止數據庫查詢

[英]Vert.x request handler and blocking db queries

如何在vert.x中正確翻譯這段代碼?

通常,在春季或帶有模板引擎的簡單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
}

問題是,從數據庫中檢索數據是asyncresult的處理程序,所以我不能授予模板評估是使用data1或data2進行的,因為檢索異步時不會掉入回調地獄。

我不太了解rxjava2,但是我覺得我想用勺子殺死豆子。

您可以使用期貨成分 ComposeExamplevertx-examples回購:

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;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM