如何为实体分配唯一编号.
唯一的数字范围将由用户定义,例如1000000001所以接下来
数字将是1000000002,依此类推.
目前我正在维护一个单独的实体来管理我的其他实体的编号范围.
在保存任何实体时我现在正在做什么.我读取了我的号码范围实体并选择了那里更新的最后一个号码并将该号码增加1并将该号码分配给我要保存的实体.之后,我将使用更新的号码保存我的号码范围实体.
问题:由于它是一个Web应用程序,因此可以同时访问多个用户.如果多个用户同时保存同一实体,则将相同的唯一编号分配给多个记录.
如何克服这个问题?
如果按实体编号指的是实体的密钥名称/标识符,则防止将相同编号分配给不同记录的唯一方法是预先保留它们.从
Assigning identifiers开始:
Note: Instead of using key name strings or generating numeric IDs automatically,advanced applications may sometimes wish to assign
their own numeric IDs manually to the entities they create. Be aware,
however,that there is nothing to prevent Cloud Datastore from
assigning one of your manual numeric IDs to another entity. The only
way to avoid such conflicts is to have your application obtain a block
of IDs with the methods 07001 or
07002. Cloud Datastore’s
automatic ID generator will keep track of IDs that have been allocated
with these methods and will avoid reusing them for another entity,so
you can safely use such IDs without conflict.
无论使用数字作为密钥名称/标识符还是仅作为属性值,为了防止多个同时请求分配相同的数字,您需要在单个事务中执行所有这些操作:
>读取存储最后指定值的最后分配的实体
>递增值以获取当前数字
>在最后分配的实体中保存当前号码
>如果适用,分配如上所述的新标识符
>使用当前编号创建新实体
您的代码应准备好重试整个事务,因为当多个请求同时尝试执行时,它将失败 – 只有一个(最大)将成功更新最后分配的实体.
使用密钥名称/标识符或仅属性的这种递增值可能会导致“热片”数据存储区可伸缩性问题,从而影响读/写/索引操作的性能,这一点毫无价值.从High read/write rates to a narrow key range开始:
If you are using Cloud Datastore,you can get slow writes due to a hot
tablet if you have a sudden increase in the write rate to a small
range of keys that exceeds the capacity of a single tablet server.
Bigtable will eventually split the key space to support high load.
…
By default,Cloud Datastore allocates keys using a scattered
algorithm. Thus you will not normally encounter hotspotting on Cloud
Datastore writes if you create new entities at a high write rate using
the default ID allocation policy. There are some corner cases where
you can hit this problem:
- If you create new entities at a very high rate and you are allocating your own IDs which are monotonically increasing.
…
- You will also see this problem if you create new entities at a high rate with a monotonically increasing indexed property like a timestamp,because these properties are the keys for rows in the index tables in Bigtable.