MongoDB 互斥
Mutex with MongoDB
我有多台服务器共享一个 mongodb。在数据库中有一个作业列表,服务器必须完成。因为我想在所有服务器上分配负载并希望避免多个服务器执行相同的工作,所以我想“锁定”该工作。
我的想法是:
如果元素尚未被采纳,则设置为采纳:
db.collection.update({done: false, taken: false},{$set: {taken: true, takenBy: myIp}});
检查服务器是否在该元素上获得了互斥:db.collection.findOne({taken: true, takenBy: myIp})
这是否是通过 mongodb“同步”多个工作服务器的最佳方式(服务器是否像 mysql 那样在单个事务中执行更新)或者服务器是否可以执行多个这样的操作立即执行第一个命令?
此区域的关键 MongoDB 功能是对 单个 文档的更新是原子的。来自 the docs:
In MongoDB, a write operation is atomic on the level of a single
document, even if the operation modifies multiple embedded documents
within a single document.
When a single write operation modifies multiple documents, the
modification of each document is atomic, but the operation as a whole
is not atomic and other operations may interleave. However, you can
isolate a single write operation that affects multiple documents using
the $isolated
operator.
所以对于你的更新:
db.collection.update({done: false, taken: false},{$set: {taken: true, takenBy: myIp}});
这意味着它将自动找到符合条件的文档,然后更新它。所以是的,将任务分配给给定服务器会很有效。
请参阅 this other post for more details on implementing a shared work queue in MongoDB. A key point that's mentioned there is the use of findAndModify
执行更新 和 return 更新的文档。
我有多台服务器共享一个 mongodb。在数据库中有一个作业列表,服务器必须完成。因为我想在所有服务器上分配负载并希望避免多个服务器执行相同的工作,所以我想“锁定”该工作。
我的想法是:
如果元素尚未被采纳,则设置为采纳:
db.collection.update({done: false, taken: false},{$set: {taken: true, takenBy: myIp}});
检查服务器是否在该元素上获得了互斥:
db.collection.findOne({taken: true, takenBy: myIp})
这是否是通过 mongodb“同步”多个工作服务器的最佳方式(服务器是否像 mysql 那样在单个事务中执行更新)或者服务器是否可以执行多个这样的操作立即执行第一个命令?
此区域的关键 MongoDB 功能是对 单个 文档的更新是原子的。来自 the docs:
In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document.
When a single write operation modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic and other operations may interleave. However, you can isolate a single write operation that affects multiple documents using the
$isolated
operator.
所以对于你的更新:
db.collection.update({done: false, taken: false},{$set: {taken: true, takenBy: myIp}});
这意味着它将自动找到符合条件的文档,然后更新它。所以是的,将任务分配给给定服务器会很有效。
请参阅 this other post for more details on implementing a shared work queue in MongoDB. A key point that's mentioned there is the use of findAndModify
执行更新 和 return 更新的文档。