【问题标题】:How to move from deprecated Task to ApiFuture for firebase admin SDK 5.4 and above如何从已弃用的 Task 转移到 Firebase admin SDK 5.4 及更高版本的 ApiFuture
【发布时间】:2023-04-01 11:49:02
【问题描述】:

我只是想从我的新 firebase-admin SDK 的 Java 代码中解决弃用说明,该代码是在 5.3.1 版本中编写的,但是在将版本升级到 5.5.0 后出现了弃用说明,这里是我的代码示例:

使用 FirebaseAuth(已弃用:TaskaddOnSuccessListeneraddOnFailureListener):

private CompletableFuture<FirebaseToken> getDecryptedTokenCompletableFuture(String firebaseTokenString) {
        CompletableFuture<FirebaseToken> tokenFuture = new CompletableFuture<>();
        Task<FirebaseToken> tokenTask = FirebaseAuth.getInstance(firebaseApp).verifyIdToken(firebaseTokenString);
        tokenTask.addOnSuccessListener(tokenFuture::complete);
        tokenTask.addOnFailureListener(exception -> tokenFuture.completeExceptionally(new AuthorizationException("Failed to verify token", exception)));
        return tokenFuture;
    }

对于 FirebaseDatabase(已弃用:TaskaddOnSuccessListeneraddOnFailureListenerupdateChildrenremoveValue):

public static <T> CompletableFuture<T> toCompletableFuture(Task<T> task) {
    CompletableFuture<T> future = new CompletableFuture<>();
    task.addOnCompleteListener(result -> {
        future.complete(result.getResult());
    }).addOnFailureListener(future::completeExceptionally);
    return future;
}

/**
 * @param updatedParams if null it will removed child
 * @param path          path to update
 * @return void when complete
 */
public CompletableFuture<Void> updateObjectData(Map<String, Object> updatedParams, String path) {
    if (updatedParams == null) {
        return removeObjectData(path);
    }
    logger.debug("Update ObjectData in firebase of ref ({}) with data: {}", path, updatedParams.toString());
    DatabaseReference child = this.getUserDataReference().child(path);
    return toCompletableFuture(child.updateChildren(updatedParams));
}

/**
 * @param path path to of node to remove
 * @return void when complete
 */
public CompletableFuture<Void> removeObjectData(String path) {
    logger.debug("Remove ObjectData in firebase of ref ({})", path);
    DatabaseReference child = this.getUserDataReference().child(path);
    return toCompletableFuture(child.removeValue());
}

弃用说明说我必须使用 ApiFuture 作为发行说明所说的:https://firebase.google.com/support/release-notes/admin/java

还有内源,比如:

  /**
   * Similar to {@link #updateChildrenAsync(Map)} but returns a Task.
   *
   * @param update The paths to update and their new values
   * @return The {@link Task} for this operation.
   * @deprecated Use {@link #updateChildrenAsync(Map)}
   */

/**
 * Represents an asynchronous operation.
 *
 * @param <T> the type of the result of the operation
 * @deprecated {@code Task} has been deprecated in favor of
 *     <a href="https://googleapis.github.io/api-common-java/1.1.0/apidocs/com/google/api/core/ApiFuture.html">{@code ApiFuture}</a>.
 *     For every method x() that returns a {@code Task<T>}, you should be able to find a
 *     corresponding xAsync() method that returns an {@code ApiFuture<T>}.
 */

【问题讨论】:

  • 您是否尝试过研究新 API 以了解其工作原理?
  • @DougStevenson 如果您的意思是 firebase.google.com/docs/database/adminfirebase.google.com/docs/database/android 如果您的意思是 addListener(Runnable listener, Executor executor),该文档似乎仍然适用于旧版本并且尚未更新,这就是我要问的 @987654338 @ 或者说我该怎么做toCompletableFuture 部分

标签: java firebase java-8 firebase-admin


【解决方案1】:

使用 ApiFuture 从 Firebase Admin SDK Java 验证带有 FirebaseAuth 的令牌的代码是:

ApiFutures.addCallback(FirebaseAuth.getInstance().verifyIdTokenAsync(token),
  new ApiFutureCallback<FirebaseToken>() {
      @Override
      public void onFailure(Throwable t) {
        // TODO handle failure
      }
      @Override
      public void onSuccess(FirebaseToken decodedToken) {
        // TODO handle success
      }
});

类似的方法可用于您使用 FirebaseDatabase 的代码。

Hiranya Jayathilaka 写了一篇非常详细的文章,解释了如何从 Task 迁移到 ApiFuture 及其背后的理性:https://medium.com/google-cloud/firebase-asynchronous-operations-with-admin-java-sdk-82ca9b4f6022

此代码适用于 5.4.0 - 5.8.0 版本,这是撰写本文时的最新版本。 发布说明可在此处获得:https://firebase.google.com/support/release-notes/admin/java

【讨论】:

    【解决方案2】:

    看看ApiFutures util 类,它允许向ApiFuture 添加回调。

    【讨论】:

    • 有意思,我去看看
    • 不错的答案,伙计!谢谢!
    【解决方案3】:

    快 2 年了,但需要添加我的答案,当前的答案给了我一个指导,但不是一个完整的解决方案,所以 @Enylton Machado@Hiranya Jayathilaka 的荣誉仍然很好参考他们的答案,给他们点赞.

    目前,我确实将toCompletableFuture 更改为:

    public <T> CompletableFuture<T> toCompletableFuture(ApiFuture<T> apiFuture) {
        final CompletableFuture<T> future = new CompletableFuture<>();
        apiFuture.addListener(() -> {
            try {
                future.complete(apiFuture.get());
            } catch (InterruptedException | ExecutionException ex) {
                logger.error(ex.getMessage());
                future.completeExceptionally(ex);
            }
        }, executionContext);
        return future;
    }
    

    executionContext 在构造函数中被注入,因为我使用的是 Play 框架,或者您可以使用 Executors.newFixedThreadPool(10) 初始化自己的,例如!但是你需要处理关闭它和其他事情,更多细节可以从这里了解ExecutorService in JavaA Guide to the Java ExecutorService

    所以当我像this.getUserDataReference().child(path).push().setValueAsync(value) 那样打电话时,我会这样称呼它:

    public CompletableFuture<String> pushDataToArray(String path, Map<String, Object> paramsToAdd) {
        final DatabaseReference databaseReference = getUserDataReference().child(path).push();
        paramsToAdd.put("createdAt", ServerValue.TIMESTAMP);
    
        return toCompletableFuture(databaseReference.setValueAsync(paramsToAdd), this.executionContext)
                .thenApply(voidResult -> databaseReference.getKey());
    }
    

    编辑:如果你喜欢使用ApiFutures

    public <T> CompletableFuture<T> toCompletableFuture(ApiFuture<T> apiFuture) {
        final CompletableFuture<T> future = new CompletableFuture<>();
        ApiFutures.addCallback(apiFuture, new ApiFutureCallback<T>() {
            @Override
            public void onFailure(Throwable t) {
                future.completeExceptionally(t);
            }
    
            @Override
            public void onSuccess(T result) {
                try {
                    future.complete(apiFuture.get());
                } catch (InterruptedException | ExecutionException ex) {
                    logger.error(ex.getMessage());
                    future.completeExceptionally(ex);
                }
            }
        }, executionContext);
        return future;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-23
      • 2022-01-09
      • 2016-11-04
      • 2021-11-17
      • 1970-01-01
      • 2019-01-23
      • 2020-12-17
      相关资源
      最近更新 更多