【发布时间】:2026-02-02 13:35:02
【问题描述】:
我对事务还是有点困惑,不管是使用 DatastoreService 还是 Objectify。 (是的,我读过What is the correct way to atomically increment a counter in App Engine?)。我需要原子地增加一个计数器。我怎么做?应用引擎文档中的示例在其 finally 块中有一个回滚。但我不想要回滚,我希望系统继续尝试。另一方面,objectify 文档说它的事务模型与低级 api 的不同。所以我正在编写这两个代码,我只需要帮助纠正它们或确认它们。
DatastoreService 版本
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService()
Transaction txn = datastore.beginTransaction();
try {
Key commentKey = KeyFactory.createKey(“Comment”, id);
Entity comment = datastore.get(commentKey);
int views = (Integer)comment.getProperty(“views”);
views++;//increment step
comment.setProperty(“views”, views);
datastore.put(comment);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
对象化版本
ofy().transact(new VoidWork() {
@Override
public void vrun() {
Comment comment = ofy().load().type(Comment.class).id(commentId).now();
long views = 1+ comment.getViews();
comment.setViews(views);
ofy().save().entity(comment).now();
}
});
重要的一点是,我希望系统继续无限尝试。当然,我希望客户端调用在所有这些异步发生时返回。感谢您的帮助
【问题讨论】:
-
如果您将“永远尝试”作为其复杂的需要来自任务队列的消息传递包含在内,则问题的范围太广
-
永远,我的意思是我真的希望计数器非常准确,而在 DatastoreService 版本中有回滚,我不确定它尝试了多少次。
-
appengine 前端有 1 分钟的限制,所以此时它很复杂,因为您需要处理很多情况
-
你应该看看如何与具有强大原子指令的 memcached 结合使用。但过于宽泛,无法放在这里。其他答案提到了这一点。
-
@ZigMandel 我的两个答案不正确吗?他们缺少什么?我对objectify特别感兴趣,尽力而为是否正确?
标签: google-app-engine google-cloud-endpoints google-cloud-datastore objectify