【问题标题】:How do we convert a reactive JDBC call in java to a Future in scala?我们如何将 java 中的反应式 JDBC 调用转换为 scala 中的 Future?
【发布时间】:2020-05-13 07:33:10
【问题描述】:

在此处查看示例:https://github.com/vietj/reactive-pg-client

// Pool options
PgPoolOptions options = new PgPoolOptions()
  .setPort(5432)
  .setHost("the-host")
  .setDatabase("the-db")
  .setUser("user")
  .setPassword("secret")
  .setMaxSize(5);

// Create the client pool
PgPool client = PgClient.pool(options);

// A simple query
client.query("SELECT * FROM users WHERE id='julien'", ar -> {
  if (ar.succeeded()) {
    PgResult<Row> result = ar.result();
    System.out.println("Got " + result.size() + " results ");
  } else {
    System.out.println("Failure: " + ar.cause().getMessage());
  }

  // Now close the pool
  client.close();
});

如何从中获得未来?理想情况下,我们可以按照以下方式编写代码:

val f: Future[...] = clientF.query("select ...")

【问题讨论】:

    标签: scala jdbc future reactive


    【解决方案1】:

    你可以尝试使用promise:

    import scala.concurrent._
    
    def fetch(query: String): Future[PgRowSet] = {
    
      val options = new PgPoolOptions()
          .setPort(5432)
          .setHost("the-host")
          .setDatabase("the-db")
          .setUser("user")
          .setPassword("secret")
          .setMaxSize(5)
    
      val client = PgClient.pool(options)
    
      val p = Promise[PgRowSet]()
    
      client.query(query, ar => {
          if (ar.succeeded) {
            p.success(ar.result()) //resolve promise as sucessful
          } else {
            p.failure(ar.cause()) //reject promise
          }
          client.close
      })
    
      p.future
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 2019-09-01
      • 2019-09-29
      • 1970-01-01
      • 2015-07-30
      • 2019-10-25
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      相关资源
      最近更新 更多