【问题标题】:How to use transactions in Cloud Datastore如何在 Cloud Datastore 中使用事务
【发布时间】:2015-07-01 01:01:46
【问题描述】:

我想通过 Java 使用 Cloud Compute 中的 Datastore,我正在关注 Getting started with Google Cloud Datastore

我的用例非常标准 - 读取一个实体(查找),修改它并保存新版本。我想在事务中执行此操作,这样如果两个进程执行此操作,第二个进程不会覆盖第一个进程所做的更改。

我设法发出了一笔交易并且它有效。但是我不知道如果交易失败会发生什么:

  • 如何识别失败的交易?可能会抛出带有特定代码或名称的 DatastoreException?
  • 我应该明确发出回滚吗?我可以假设如果事务失败,则不会写入任何内容吗?
  • 我应该重试吗?
  • 有这方面的文档吗?

【问题讨论】:

    标签: google-cloud-datastore


    【解决方案1】:

    如何识别失败的交易?可能是 DatastoreException 会抛出一些特定的代码或名称?

    您的代码应始终确保事务成功提交或回滚。这是一个例子:

    // Begin the transaction.
    BeginTransactionRequest begin = BeginTransactionRequest.newBuilder()
        .build();
    ByteString txn = datastore.beginTransaction(begin)
      .getTransaction();
    try {
      // Zero or more transactional lookup()s or runQuerys().
      // ...
    
      // Followed by a commit().
      CommitRequest commit = CommitRequest.newBuilder()
          .setTransaction(txn)
          .addMutation(...)
          .build();
      datastore.commit(commit);
    } catch (Exception e) {
      // If a transactional operation fails for any reason,
      // attempt to roll back. 
      RollbackRequest rollback = RollbackRequest.newBuilder()
          .setTransaction(txn);
          .build();
      try {
        datastore.rollback(rollback);
      } catch (DatastoreException de) {
        // Rollback may fail due to a transient error or if
        // the transaction was already committed.
      }
      // Propagate original exception.
      throw e;
    }
    

    commit()try 块内的另一个 lookup()runQuery() 调用可能会引发异常。在每种情况下,清理事务都很重要。

    我应该明确发出回滚吗?我可以假设如果一个 交易失败,什么都不会被写入?

    除非您确定commit() 成功,否则您应该明确发出rollback() 请求。但是,失败的commit() 并不一定意味着没有数据被写入。请参阅this page 上的说明。

    我应该重试吗?

    您可以使用指数退避重试。但是,频繁的事务失败可能表明您过于频繁地尝试写入 entity group

    有这方面的文档吗?

    https://cloud.google.com/datastore/docs/concepts/transactions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-08
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      相关资源
      最近更新 更多