【问题标题】:Concurrent Read/Write in MongoDBMongoDB中的并发读/写
【发布时间】:2016-10-05 09:23:24
【问题描述】:

我有一个集合,我从中获取最大 id,并在使用 max id + 1 插入时。id 列在此集合中是唯一的。

当调用此服务的多个实例时,并发应用程序读取同一个集合并获取最大 ID。但是由于访问了同一个集合,因此将相同的 max id 返回给多个实例,我可以在从该集合中读取数据时获得该集合的显式锁定,并在写入 Mongo DB 后释放锁定吗?

【问题讨论】:

  • 您是否尝试过使用外部同步或内置同步集合?
  • 能否请您详细说明一下,我们在 MongoDB 中有同步集合吗?
  • 你能多写一点你想要达到的目标吗?看起来你需要事务,所以也许 MongoDB 不是这里的最佳选择。如果您只需要原子方式来增加一些计数器,请考虑 auto incrementing sequence field$inc
  • 应用程序是在后端是 Mongo DB 的地方编写的。我已经公开了一项服务,我们希望在 MongoDB 集合中进行自动增量。由于该服务的多个实例被暴露,多个服务试图同时访问和更新 Db,这导致了 DB 的不一致。

标签: java mongodb concurrency jvm locking


【解决方案1】:

使用 mongoDB 方法 collections.findAndModify() 您可以创建自己的“get-and-increment”查询。

例如:

db.collection_name.findAndModify({
  query: { document_identifier: "doc_id_1" },
  update: { $inc: { max_id: 1 } },
  new: true  //return the document AFTER it's updated
})

https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/

查看此页面以获得更多帮助:

https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

【讨论】:

  • 太棒了!你得到了我的。 +1。
  • 这样在执行之前,给文档加个锁吗?
【解决方案2】:

试试这个方法

而不是在读取集合时获取max id 并将其递增为max id + 1

读取多个实例时只需给出文档/集合,更新时遵循以下逻辑

Let us have the below part in a synchronized block, so that no two threads gets the same max id
synchronize() {
  getMaxId from collection
  increase it by 1
  insert the new document
}

请参考:

https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/

https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多