【发布时间】:2012-04-26 03:54:11
【问题描述】:
希望有人可以帮助我了解我是否遇到了问题,或者我只是不了解 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 时间。我真的不想为了避免在应用程序启动时出现这个问题而放入一条虚假记录。
【问题讨论】:
-
无限地阻塞某事绝不是一个好主意
-
告诉 gobject.MainLoop().run() ;)