如何在GAE数据存储中保存实体时,只有在GAE数据存储中不存在竞争条件时才存在 [英] How to save an entity in GAE datastore only if it does not exist while preventing race conditions

查看:110
本文介绍了如何在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

这篇关于如何在GAE数据存储中保存实体时,只有在GAE数据存储中不存在竞争条件时才存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆