使用 pymongo 可尾游标在空集合上死亡



希望有人能帮助我了解我是否看到了问题,或者我只是不了解mongodb可尾光标行为。我正在运行 mongodb 2.0.4 和 pymongo 2.1.1。

下面是演示问题的脚本。

#!/usr/bin/python
import sys
import time
import pymongo
MONGO_SERVER = "127.0.0.1"
MONGO_DATABASE = "mdatabase"
MONGO_COLLECTION = "mcollection"
mongodb    = pymongo.Connection(MONGO_SERVER, 27017)
database   = mongodb[MONGO_DATABASE]
if MONGO_COLLECTION in database.collection_names():
  database[MONGO_COLLECTION].drop()
print "creating capped collection"
database.create_collection(
  MONGO_COLLECTION,
  size=100000,
  max=100,
  capped=True
)
collection = database[MONGO_COLLECTION]
# Run this script with any parameter to add one record
# to the empty collection and see the code below
# loop correctly
#
if len(sys.argv[1:]):
  collection.insert(
    {
      "key" : "value",
    }
  )
# Get a tailable cursor for our looping fun
cursor = collection.find( {},
                          await_data=True,
                          tailable=True )
# This will catch ctrl-c and the error thrown if
# the collection is deleted while this script is
# running.
try:
  # The cursor should remain alive, but if there
  # is nothing in the collection, it dies after the
  # first loop. Adding a single record will
  # keep the cursor alive forever as I expected.
  while cursor.alive:
    print "Top of the loop"
    try:
      message = cursor.next()
      print message
    except StopIteration:
      print "MongoDB, why you no block on read?!"
      time.sleep(1)
except pymongo.errors.OperationFailure:
  print "Delete the collection while running to see this."
except KeyboardInterrupt:
  print "trl-C Ya!"
  sys.exit(0)
print "and we're out"
# End

因此,如果您查看代码,演示我遇到的问题非常简单。当我针对空集合(正确封顶并准备好进行跟踪)运行代码时,游标死亡,我的代码在循环后退出。在集合中添加第一条记录使其行为方式与我希望尾随光标的行为方式相同。

另外,StopIteration异常杀死了等待数据的cursor.next()是怎么回事?为什么后端不能在数据可用之前阻止?我以为await_data实际上会做一些事情,但它似乎只会让连接等待一两秒钟,而不是没有它。

网络上的大多数示例都显示,在 cursor.alive 循环周围放置了第二个 While True 循环,但是当脚本尾随一个空集合时,循环只是旋转并旋转,浪费 CPU 时间。我真的不想为了在应用程序启动时避免这个问题而放入一个虚假记录。

这是已知行为,2 个循环"解决方案"是解决这种情况的公认做法。如果集合为空,而不是像您建议的那样立即重试并进入紧密循环,您可以睡一小段时间(特别是如果您预计很快就会有数据要尾部)。

最新更新