如何使用 Java 确定 Google AppEngine 数据存储区中给定键的对象是否存在?
我正在尝试将分片计数器示例 (code.google.com/appengine/articles/sharding_counters.html) 移植到 Java。 唯一的问题是 Java API 没有类似于 Python 的“get_by_key_name”的调用。 这是基本思想:
Transaction tx = pm.currentTransaction();
Key key = KeyFactory.createKey(CounterShard.class.getSimpleName(), counter + randomIndex);
CounterShard shard = pm.getObjectById(CounterShard.class, key);
if (shard == null) { // API does not work this way...
shard = new CounterShard(key, counter);
}
shard.increment();
pm.makePersistent(shard);
tx.commit();
不幸的是,当我第一次运行它时,它会抛出一个 JDOObjectNotFoundException 。 我可以运行一个查询来确定给定名称的计数器是否存在,但这不是事务性的。 另一个线程可以做同样的事情,最终两个线程都会创建一个具有相同键的对象。
据我了解,事务(对于 Java API)中支持的唯一操作是 get 和 put。 那么我怎样才能通过键锁定一个尚不存在的对象(即没有“get”)并确保我是第一个也是唯一一个创建它的人?
I'm trying to port the Sharding Counters example (code.google.com/appengine/articles/sharding_counters.html) to Java. The only problem is that the Java API does not have a call similar to Python's 'get_by_key_name'. This is the basic idea:
Transaction tx = pm.currentTransaction();
Key key = KeyFactory.createKey(CounterShard.class.getSimpleName(), counter + randomIndex);
CounterShard shard = pm.getObjectById(CounterShard.class, key);
if (shard == null) { // API does not work this way...
shard = new CounterShard(key, counter);
}
shard.increment();
pm.makePersistent(shard);
tx.commit();
Unfortunately, this throws a JDOObjectNotFoundException the first time I run it. I could run a query to determine if a counter for a given name exists, but that is not transactional. Another thread could do the same and in the end both would create an object with the same key.
From what I understand, the only operations supported within a transaction (for the Java API) are get and put. So how can I lock an object by key that does not exist yet (i.e. no 'get') and make sure that I am the first and only one creating it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在此处查看演示代码
http://code .google.com/p/googleappengine/source/browse/trunk/java/demos/shardedcounter/README
check the demo code here
http://code.google.com/p/googleappengine/source/browse/trunk/java/demos/shardedcounter/README