gpt4 book ai didi

mongodb - Spring Data MongoDB 并发更新行为

转载 作者:行者123 更新时间:2023-12-03 15:59:34 25 4
gpt4 key购买 nike

假设有一个包含单个字段的文档:{availableSpots: 100}

有数百万用户竞相通过向 API 服务器发送请求来获得席位。

每次收到请求时,服务器都会读取文档,如果 availableSpot > 0,则会将其减 1 并在另一个集合中创建预订。

现在我读到,每当执行更新操作时,mongodb 都会锁定文档。

如果有一百万个并发请求会发生什么?是否会因为同一个文档不断被锁定而需要很长时间?此外,服务器在尝试更新文档之前会读取文档的值,并且当它获取锁时,该位置可能不再可用。

线程也有可能在同一时刻获得“availableSpot > 0”为真,但实际上,availableSpot 可能不足以满足所有请求。怎么处理这个问题?

最佳答案

这里最重要的是原子性和并发性。

<强>1。原子性

如果 availableSpots > 0,则执行更新操作(减一):

db.collection.updateOne({"availableSpots" :{$gt : 0}}, { $inc: { availableSpots: -1 })

是原子的。

$inc is an atomic operation within a single document.

引用:https://docs.mongodb.com/manual/reference/operator/update/inc/

<强>2。并发由于MongoDB对写操作有文档级的并发控制。每次更新都会锁定文档。

现在你的问题:

What will happen if theres a million concurrent requests?

是的,每次更新都会一一执行(由于锁定),因此速度会变慢。

the server reads the value of document before it tries to update the document, and by the time it acquires the lock, the spot may not be available anymore.

由于该操作是原子操作,因此不会发生这种情况。它将按照您的意愿工作,仅执行 100 次更新,且受影响的行数大于 0 或等于 1。

关于mongodb - Spring Data MongoDB 并发更新行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56713196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com