【问题标题】:How to use MongoDB Async Java Driver in Play Framework 2.x action?如何在 Play Framework 2.x 操作中使用 MongoDB Async Java 驱动程序?
【发布时间】:2015-10-24 11:38:15
【问题描述】:

我想在 Play Framework 2 项目中使用 MongoDB Async Java Driver,MongoDB Async Java Driver 返回 SingleResponseCallback。 我不知道如何在 Play 控制器中处理这种结果。

例如如何在 Play 控制器中从以下代码返回计数:

collection.count(
 new SingleResultCallback<Long>() {
  @Override
  public void onResult(final Long count, final Throwable t) {
      System.out.println(count);
  }
});

如何从 SingleResultCallback 获取结果,然后将其转换为 Promise?这是好方法吗?在这种情况下,最佳做法是什么?

【问题讨论】:

    标签: mongodb asynchronous playframework callback nonblocking


    【解决方案1】:

    你必须自己解决这个承诺。请记住,Play 承诺是 scala 期货的包装,解决未来的唯一方法是使用 scala Promises(与 play 承诺不同)(我知道,这有点令人困惑)。你必须这样做:

    Promise<Long> promise = Promise$.MODULE$.apply();
    collection.count(
     new SingleResultCallback<Long>() {
       @Override
       public void onResult(final Long count, final Throwable t) {
         promise.success(count);
      }
    });
    return F.Promise.wrap(promise.future());
    

    Promise$.MODULE$.apply() 就是从 java 访问 scala 对象的方式。

    【讨论】:

    • 感谢您的回复。它解决了我的问题。我将添加一个包含更多详细信息的新答案。
    【解决方案2】:

    感谢@caeus 的回答,这是详细信息:

    public F.Promise<Result> index() {
        return F.Promise.wrap(calculateCount())
                .map((Long response) -> ok(response.toString()));
    }
    
    
    private Future<Long> calculateCount() {
        Promise<Long> promise = Promise$.MODULE$.apply();
    
        collection.count(
                new SingleResultCallback<Long>() {
                    @Override
                    public void onResult(final Long count, final Throwable t) {
                        promise.success(count);
                    }
                });
    
        return promise.future();
    }
    

    【讨论】:

      【解决方案3】:

      更清洁的解决方案是使用F.RedeemablePromise&lt;A&gt;

      public F.Promise<Result> index() {
          F.RedeemablePromise<Long> promise = F.RedeemablePromise.empty();
      
          collection.count(new SingleResultCallback<Long>() {
              @Override
              public void onResult(final Long count, final Throwable t) {
                  promise.success(count);
              }
          });
      
          return promise.map((Long response) -> ok(response.toString()));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        • 1970-01-01
        相关资源
        最近更新 更多