gpt4 book ai didi

python - MongoDB M0集群,python多线程

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:06 26 4
gpt4 key购买 nike

我有一个 python 应用程序,可以进行网络抓取并利用 mongo 数据库来维护记录。在执行过程中的某些时刻,会有大量的数据库请求传入和传出。发生这种情况时,服务器会强制关闭我的请求,并在集群中给出以下错误:

配置限制的连接百分比已超过 80

将 pymongo 与线程结合使用的最佳实践是什么?我认为其他 DMBS 的 mongodb 会自动处理并发请求的调度。我是否需要创建一个本地集群或将当前集群升级为更多连接?

最佳答案

这种情况下的典型事件是创建输入队列。队列并将任务放入其中,并创建多个工作人员以从队列中获取任务。如果您需要限制可以同时访问资源的工作人员数量,请使用 threading.Semaphore 或 threading.Lock 希望答案对您有所帮助,请随时提出问题。

import threading as thr
from queue import Queue


def work(input_q):
"""the function take task from input_q and print or return with some code changes (if you want)"""
while True:
item = input_q.get()
if item == "STOP":
break

# else do some work here
print("some result")


if __name__ == "__main__":
input_q = Queue()
urls = [...]
threads_number = 8 # experiment with the number of workers
workers = [thr.Thread(target=work, args=(input_q,),) for i in range(threads_number)]
# start workers here
for w in workers:
w.start

# start delivering tasks to workers
for task in urls:
input_q.put(task)

# "poison pillow" for all workers to stop them:

for i in range(threads_number):
input_q.put("STOP")

# join all workers to main thread here:

for w in workers:
w.join

# show that main thread can continue

print("Job is done.")

关于python - MongoDB M0集群,python多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58438448/

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