gpt4 book ai didi

python - 使用 pymongo tailable 游标死于空集合

转载 作者:可可西里 更新时间:2023-11-01 09:53:06 28 4
gpt4 key购买 nike

希望有人能帮助我理解我是否遇到了问题,或者我是否只是不理解 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

因此,如果您查看代码,就可以非常简单地证明我遇到的问题。当我针对一个空集合(正确封顶并准备拖尾)运行代码时,游标消失并且我的代码在一个循环后退出。在集合中添加第一条记录使其行为方式与我期望的尾游标行为方式相同。

此外,终止 cursor.next() 等待数据的 StopIteration 异常的处理方式是什么?为什么后端不能阻塞直到数据可用?我假设 await_data 实际上会做一些事情,但它似乎只比没有它时让连接等待一两秒。

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

最佳答案

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

关于python - 使用 pymongo tailable 游标死于空集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10321140/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com