How to use transactions in Cloud Datastore

时间:2015-06-30 13:39:26

标签: google-cloud-datastore

I want to use Datastore from Cloud Compute through Java and I am following Getting started with Google Cloud Datastore.

My use case is quite standard - read one entity (lookup), modify it and save the new version. I want to do it in a transaction so that if two processes do this, the second one won't overwrite the changes made by the first one.

I managed to issue a transaction and it works. However I don't know what would happen if the transaction fails:

  • How to identify a failed transaction? Probably a DatastoreException with some specific code or name will be thrown?
  • Should I issue a rollback explicitly? Can I assume that if a transaction fails, nothing from it will be written?
  • Should I retry?
  • Is there any documentation on that?

1 个答案:

答案 0 :(得分:2)

  

如何识别失败的交易?可能是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()lookup()块内的其他runQuery()try调用可能会引发异常。在每种情况下,清理交易都很重要。

  

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

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

  

我应该重试吗?

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

  

有没有相关的文件?

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