我有一个脚本,它用完本地运行的 MongoDB 的所有可用连接,然后存在以下错误消息:
pymongo.errors.AutoReconnect: [Errno 4] Interrupted system call
/var/log/mongodb/mongod.log 中的错误消息是:
[initandlisten] connection refused because too many open connections: 819
调用脚本时,Mongo-Shell 会给出以下输出:
> db.serverStatus().connections
{ "current" : 1, "available" : 818 } // Script not yet started
> db.serverStatus().connections
{ "current" : 400, "available" : 419 } // Losing connections
> db.serverStatus().connections
{ "current" : 638, "available" : 181 }
> db.serverStatus().connections
{ "current" : 804, "available" : 15 }
> db.serverStatus().connections
{ "current" : 819, "available" : 0 } // Script terminates
> db.serverStatus().connections
{ "current" : 1, "available" : 818 } // Script terminated
我无法发布原始脚本,但下面的“净化”片段希望能提供一个想法。基本上,我在多个集合中运行各种不同的查询和更新。
最重要的是,11 个数据库语句中只有 5 个有时不会释放它们的连接。其他 6 个语句将始终留下与语句之前一样多的空闲连接。
mc = pymongo.Connection()
db = mc.database
def available():
""" Return the number of available connections """
return db.command("serverStatus")['connections']['available']
def process():
while True:
# ...
# Connections lost:
conns = available()
coll_a = db.coll_a.find_and_modify(
query={'x': x},
update={'$pop': {'x': -1}},
fields={'x': 1})
if conns > available():
print('Fewer connections')
# ...
# No connections lost:
db.coll_a.update({'x': x}, {'$pullAll': {'x': [x]}})
# ...
# No connections lost:
coll_d = db.coll_d.find_and_modify(
query={'x': x,},
update={'$set': {'x': x}},
fields={'x': 1})
# ...
# No connections lost:
coll_b_cursor = db.coll_b.find({'x': x}, {'x': 1})
# ...
# No connections lost:
coll_e_cursor = db.coll_e.find({'$or': [{'x': x}, {'x': x}]})
# ...
for item in coll_e_cursor:
# No connections lost:
coll_b = db.coll_b.find({'x': x}).count()
# ...
# No connections lost:
coll_b_cursor = db.coll_b.find({'x': x}, {'x': x})
# ...
for x in y:
if x:
# Connections lost:
conns = available()
db.coll_b.update({'x': x}, {'$unset': {'x': 1}})
if conns > available():
print('Fewer connections')
# ...
# Connections lost:
conns = available()
coll_b = db.coll_b.find_and_modify(
query={'x': x},
update={'$set': {'x': x}},
fields={'x': 1},
upsert=True)
if conns > available():
print('Fewer connections')
# ...
# Connections lost:
conns = available()
coll_c_1 = db.coll_c.find_one({'x': x})
coll_c_2 = db.coll_c.find_one({'x': x})
if conns > available():
print('Fewer connections')
# ...
# Connections lost:
conns = available()
db.coll_b.update({'x': x}, {'$unset': {'x': 1}})
if conns > available():
print('Fewer connections')
- 不释放连接的语句和释放连接的语句有什么区别?
- PyMongo 或 MongoDB 在所有情况下都不应该释放连接吗?
PyMongo:2.2.1
MongoDB:2.0.6