背景
最近python接口总是报错,看了下日志,提示RuntimeError:can’t start new thread。起初以为是隔壁算法组的服务把服务器资源占满,但是他们项目重启后几天,又发生这个情况。我想大概是python接口连接mongodb后没有主动断开连接吧。
更新内容
即使在代码里加了主动关闭连接的操作,也会出现问题。查看系统进程发现设置的pid_max = 32768,当前已达到32500+,所以支持不了并发了。修改了系统的pid_max = 132768,暂时把问题解决了。
反思
代码可优化空间太大,路漫漫,继续学习吧。
方法
mongodb对象
import pymongo
class Mongo(object):
def __init__(self, db_name):
self.db_name = db_name
self.client = pymongo.MongoClient('mongodb://' + InterfaceConfig.MongoDB_URL, 27017,serverSelectionTimeoutMS=5000, socketTimeoutMS=5000)
print('数据库已连接')
self.db = self.client[self.db_name]
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('关闭数据库连接')
self.client.close()
def hello(self):
print('hello')
使用
def ur_fun():
with Mongo('test') as mongo:
# some code here
mongo.hello()

本文介绍了作者在使用Python的PyMongo库操作MongoDB时遇到的RuntimeError问题,原因是未正确关闭连接导致线程资源耗尽。通过增加系统最大进程数暂时解决,但意识到代码优化的必要,分享了如何创建和使用MongoDB对象以确保连接的正确关闭。
27

被折叠的 条评论
为什么被折叠?



