如何在GAE数据存储中保存实体时,只有在GAE数据存储中不存在竞争条件时才存在

如何在GAE数据存储中保存实体时,只有在GAE数据存储中不存在竞争条件时才存在

问题描述:

我试图将实体保存到Google App Engine数据存储区,除非它不存在,否则该线程不应继续。

I am trying to save an entity to Google App Engine Datastore only if it does not exist, if it does the thread should not continue.

主要问题是:我想阻止任何竞争条件,例如,如果两个线程同时这样做,只有一个线程可以成功保存实体。

Main issue is: I want to prevent any race conditions, such that if 2 threads are doing this at the same time only one would succeed in saving the entity.

我不确定什么是最好的方法是使用Transactions工作,或者必须依赖其他解决方案,例如使用Memcache

I am not sure what is the best approach for this, would using Transactions work or one must rely on other solutions such as using Memcache

请在java中的低级API中提供答案

Please provide answer in low level API in java

从App Engine调用Datastore 时,api不同。使用交易。首先尝试让()实体看看它是否在那里。如果没有的话,put()实体。

When calling Datastore from App Engine, the api is different. Use a transaction. First try to get() the entity to see if it's there. If not, put() the entity.

以下是一些演示使用App Engine API的示例代码:
https://github.com /GoogleCloudPlatform/java-docs-samples/blob/master/appengine/datastore/src/test/java/com/example/appengine/TransactionsTest.java

Here's some sample code that demonstrates transactions using the App Engine API: https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/appengine/datastore/src/test/java/com/example/appengine/TransactionsTest.java