【问题标题】:Cloud Datastore: ways to avoid race conditionsCloud Datastore:避免竞争条件的方法
【发布时间】:2016-08-15 13:12:17
【问题描述】:

我有很多操作相同类型实体的视图:

def view1(request, key):
    user = ndb.Key(urlsafe=key).get()
    user.x = 1
    user.put()
    ...

def view2(request, key):
    user = ndb.Key(urlsafe=key).get()
    user.y = 2
    user.put()
    ...

显然,由于可能的竞争条件(最后获胜),这很容易出错:

  1. view1 读取整个用户实体数据(x=None,y=None)
  2. view2 读取整个用户实体数据(x=None,y=None)
  3. view1 user.x = 1 (x=1, y=None)
  4. view2 user.y = 2 (x=None, y=2)
  5. view1 user.put() (x=1, y=None)
  6. view2 user.put() (x=None, y=2)

解决此问题的最佳方法是什么?什么行为被认为是最体面的?事务(其中一个请求会失败,可以吗)?

【问题讨论】:

  • 是的,使用事务是解决此类问题的典型方法。

标签: google-app-engine google-cloud-datastore gae-python27


【解决方案1】:

包装您的获取并投入交易。这将确保您不会踩到其他更新。

您可以阅读有关transactions with the NDB Client Library 文档的更多信息。

在您的代码中,例如,您可以只使用 NDB 事务装饰器:

@ndb.transactional(retries=1)
def view1(request, key):
    user = ndb.Key(urlsafe=key).get()
    user.x = 1
    user.put()
    ...

@ndb.transactional(retries=1)    
def view2(request, key):
    user = ndb.Key(urlsafe=key).get()
    user.y = 2
    user.put()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-30
    • 2010-09-25
    • 2010-09-25
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多