简体   繁体   English

如何在Play Framework 2.x操作中使用MongoDB异步Java驱动程序?

[英]How to use MongoDB Async Java Driver in Play Framework 2.x action?

I want to use MongoDB Async Java Driver in a Play Framework 2 project, MongoDB Async Java Driver return SingleResponseCallback. 我想在Play Framework 2项目中使用MongoDB Async Java Driver ,MongoDB Async Java Driver返回SingleResponseCallback。 I do not know how to handle this kind of result in Play controllers. 我不知道如何在Play控制器中处理这种结果。

For example how to return count from the following code in a Play controller: 例如,如何从Play控制器中的以下代码返回计数:

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

How can i get result from SingleResultCallback and then convert it to Promise? 我怎样才能从SingleResultCallback获得结果然后将其转换为Promise? is it good way? 这是好方法吗? What is the best practice in this situations? 在这种情况下,最佳做法是什么?

You have to resolve the promise yourself. 你必须自己解决这个承诺。 Remember that the Play promises are wrappers to scala futures and that the only way to resolve a future is using scala Promises (different from play promises) (I know, it's kinda confusing). 请记住,Play承诺是scala期货的包装器,解决未来的唯一方法是使用scala Promises(与play promises不同)(我知道,这有点令人困惑)。 You'd have to do something like this: 你必须做这样的事情:

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());

That thing about the Promise$.MODULE$.apply() is just the way to access scala objects from java. 关于Promise$.MODULE$.apply()事情只是从java访问scala对象的方法。

Thanks to @caeus answer, This is the details: 感谢@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();
}

A cleaner solution would be to use F.RedeemablePromise<A> . 更清洁的解决方案是使用F.RedeemablePromise<A>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM