云数据存储:避免竞争条件的方法 [英] Cloud Datastore: ways to avoid race conditions

查看:147
本文介绍了云数据存储:避免竞争条件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def view1(请求,键):
我有很多操作同类实体的视图: user = ndb.Key(urlsafe = key).get()
user.x = 1
user.put()
...

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

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


  1. view1读取整个用户实体数据(x = None,y = None)
  2. view2读取整个用户实体数据(x =无,y =无)

  3. view1 user.x = 1 (x = 1,y =无)

  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)


  7. 解决这个问题的最佳方法是什么? ?事务(其中一个请求会失败,这是否正常)? 解决方案

包装你的get和put到事务中。这可以确保您不会踩到其他更新。



您可以详细了解与NDB客户端库交易文档。



在你的代码中,你可以例如使用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()


I have lots of views manipulating entities of same kind:

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()
    ...

Obviously, this is error-prone due to possible race conditions (last wins):

  1. view1 reads whole user entity data (x=None, y=None)
  2. view2 reads whole user entity data (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)

What are best ways to fix this and what behaviour is considered most decent? Transactions (one of the requests is gonna fail, is this ok)?

解决方案

Wrap your get and put into a transaction. This will ensure you cannot stomp over a different update.

You can read more about transactions with the NDB Client Library documentation.

In your code, you could for example just use the NDB transaction decorator:

@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()

这篇关于云数据存储:避免竞争条件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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