Home  >  Q&A  >  body text

python - mongodb 高并发写入 覆盖原有数据

我有一个product表数据, 它会产生10个coupon, 我在product表的字段里存了coupon_count的字段为10, 如果抢红包的话根据coupon_count的剩余数来生成红包(抢红包coupon_count 减一)。

当1秒内并发上百的话, 会因为多个进程并发写入问题产生超过总是得红包。有什么方案可以解决这个问题?

  1. web框架: flask

  2. 数据库: mongodb 3.2.6

  3. 使用orm框架: mongoengine

PHP中文网PHP中文网2741 days ago374

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:43:24

    Yes, mongodb has no transactions and will not lock the table. The process from querying the number to writing is not atomic, so high concurrency will inevitably cause problems.
    It is recommended to modify the data and query interfaces to adapt to some mongodb atomic operations, such as generating red envelopes first, and then using findAndModify to query and synchronously modify the red envelope status when grabbing red envelopes.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 17:43:24

    Use findAndModify()

    reply
    0
  • Cancelreply