英文:
How to perform this in update in Go? (Google App Engine)
问题
我需要以一种不会被多个并发用户破坏的方式更新数据存储实体。我知道不能使用SQL来更新数据存储,但我不确定还有什么其他方法可以实现。
在关系型数据库管理系统(RDBMS)中,我会这样实现:
-- Account.Balance = 当前余额
-- Account.Rate = 每秒增加的金额
-- Account.CheckDate = 上次检查和更新余额的时间
-- 所以我们需要找到自上次检查以来的秒数,
-- 通过 rate*seconds 更新余额,然后更新检查日期时间
UPDATE Account
SET Account.Balance = Account.Balance + ( DATEDIFF(S, GETDATE(), Account.CheckDate) * Account.Rate),
Account.CheckDate = GETDATE()
我知道可以将所有操作包装在一个事务中,但是如何确保更新不会因为多个用户而计算错误,而不使用像SQL中所示的单个更新操作呢?你可能会发现以下几个操作可能会失败:
1. 读取实体
2. 更新值
3. 保存实体
因为多个用户同时进行相同的操作。
我猜想有几种可能的方法可以实现这一点,我正在寻找最适合当前和未来需求的方法。
================== 答案 ==================
当我达到这一点时,我意识到只要同时更新余额和检查日期,一切都会没问题。
并发更新不会破坏任何东西
但我还是想发表一下!
当然,我仍然很乐意看到更好的解决方案...
英文:
I need to update a datastore entity in a way that will not be broken by multiple concurrent users doing the same thing.<br />
I understand that I can't use SQL for updating the datastore but I'm not sure what else would work.
This is how I would achieve it in an RDBMS using SQL:
-- Account.Balance = current balance
-- Account.Rate = increase per second
-- Account.CheckDate = the last time the balance was checked and updated
-- so we need to find the number of seconds since the last check,
-- update the balance by rate*seconds, then update the check datetime
UPDATE Account
SET Account.Balance = Account.Balance + ( DATEDIFF(S, GETDATE(), Account.CheckDate) * Account.Rate),
Account.CheckDate = GETDATE()
I know that I can wrap all the operations in a single transaction, but how can I ensure that the update is not miscalculated because of multiple users without using a single update operation like the SQL shown?<br />
You can probably see that several operations like:
1. Read entity
2. Update values
3. Save entity
might fail because of several users doing the same thing
I'm guessing there are several possible ways to achieve this and I'm looking for the one which would work best for this and future requirements.
================== ANSWER ==================
When I got to this point I realised that as long as I update the balance and the check date at the same time, all will be fine.
Concurrent updates will not break anything
But I thought I'd post it anyway!
I'm still happy to see better solutions though...
答案1
得分: 2
Transactions可以用来原子地执行一系列的数据存储操作。
英文:
Transactions may be used to atomically execute a sequence of datastore operations.
答案2
得分: 0
我最终意识到只要我同时更新余额和检查日期,一切都会没问题。并发更新不会导致任何问题
但我还是想发帖分享一下!
不过我还是很乐意看到更好的解决方案...
英文:
My solution follows:
I eventually realised that as long as I update the balance and the check date at the same time, all will be fine. Concurrent updates will not break anything
But I thought I'd post it anyway!
I'm still happy to see better solutions though...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论