【问题标题】:Google Cloud Function is terminated before update to Firestore is finishedGoogle Cloud Function 在 Firestore 更新完成之前终止
【发布时间】:2022-01-06 14:44:28
【问题描述】:

我有一个从外部来源提取一些数据的云后台功能。然后这些数据应该存储在 Firestore 文档中。但它从未被存储。文档不变。这是我的代码:

public class MyFunction implements BackgroundFunction<PubSubMessage> {

   @Override
   public void accept(PubSubMessage message, Context context) {
      // pulling data from external source
      MyClass myObject = getData();
      // db is the Firestore object and was initialized earlier
      CollectionReference colRef = db.collection(MY_COL);
      DocumentReference docRef = colRef.document(MY_DOC);
      ApiFuture<WriteResult> future = docRef.set(myObject);
      ApiFutures.addCallback(future,
         new ApiFutureCallback<WriteResult>() {
            @Override
            public void onFailure(Throwable throwable) {
               logger.log(Level.SEVERE,
                  "Failed to Update Object to Firestore", throwable);
            }

            @Override
            public void onSuccess(WriteResult writeResult) {
               logger.info("Update Object Document ... DONE");
            }
         }, Runnable::run);
   }
}

来自onFailureonSuccess 的日志永远不会出现在 Firebase 信息中心的日志中。感觉就像函数在写过程完成之前就终止了。日志中没有错误,并且成功从外部源中提取数据。

如何确保函数在写入过程完成之前不会终止?

【问题讨论】:

  • 如果这些方法都没有被调用,那么你确定你有互联网连接吗?
  • 非常确定。数据通过 HTTP 调用来自外部源。该函数也在 Google Cloud 中运行。
  • 您将来可能需要调用 get() 。见stackoverflow.com/questions/60968336/…

标签: java firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

get() 必须被调用。

public class MyFunction implements BackgroundFunction<PubSubMessage> {

   @Override
   public void accept(PubSubMessage message, Context context) {
      // pulling data from external source
      MyClass myObject = getData();
      // db is the Firestore object and was initialized earlier
      CollectionReference colRef = db.collection(MY_COL);
      DocumentReference docRef = colRef.document(MY_DOC);
      ApiFuture<WriteResult> future = docRef.set(myObject);
      future.get();
   }
}

恕我直言,这是这个函数的一个误导性名称,因为它暗示未来的结果被返回,但只有在未来完成之后。我会期待像 waitAndGet()waitForFinish() 这样的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2018-06-06
    • 2020-03-02
    • 2018-06-01
    • 2021-06-01
    • 2016-10-09
    相关资源
    最近更新 更多