"pymongo MongoClient是否不能在多进程中运行?"

2024-10-01 09:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pymongo 3.2,我想在Multiforces中使用它:

client = MongoClient(JD_SEARCH_MONGO_URI, connect=False)
db = client.jd_search

with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor:
    for jd in db['sample_data'].find():
        jdId = jd["jdId"]
        for cv in db["sample_data"].find():
            itemId = cv["itemId"]
            executor.submit(intersect_compute, jdId, itemId)
            #  print "done {} => {}".format(jdId, itemId)

但我得到了错误:

^{pr2}$

根据文档,我已经将connect设置为False,如您所见


Tags: sampleinclientfalsefordbdataconnect
1条回答
网友
1楼 · 发布于 2024-10-01 09:41:22

您的做法与文档中的完全相同(URL除外),但在Never do this部分。
p、 我在评论的最后更新了你的代码示例。在

在每个进程内创建到数据库的连接:

# Each process creates its own instance of MongoClient.
def func():
    db = pymongo.MongoClient().mydb
    # Do something with db.

proc = multiprocessing.Process(target=func)
proc.start()

千万不要这样做:

^{pr2}$

您需要更改的是将数据库连接初始化移动到每个进程的一个分支。因为每个人都有自己独立的联系。在

您的样本更新:

with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor:
    client = MongoClient(JD_SEARCH_MONGO_URI, connect=False)
    db = client.jd_search

    for jd in db['sample_data'].find():
        jdId = jd["jdId"]
        for cv in db["sample_data"].find():
            itemId = cv["itemId"]
            executor.submit(intersect_compute, jdId, itemId)
            #  print "done {} => {}".format(jdId, itemId)

相关问题 更多 >