希望有人能帮助我理解我是否遇到问题或者我只是不理解 mongodb tailable 游标行为。我正在运行 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 个循环“解决方案”是解决这种情况的公认做法。在集合为空的情况下,您可以休眠一小段时间(特别是如果您预计很快就会有数据尾部),而不是像您建议的那样立即重试并进入紧密循环。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)