我有一个python应用程序,它通过web抓取并利用mongo数据库来维护记录。在执行中的某些点上,有大量的db请求传入和传出。当发生这种情况时,服务器会强制关闭我的请求,并在集群中给出以下错误:
Connections % of configured limit has gone above 80
在线程中使用pymongo的最佳实践是什么?我想像其他DMBS一样,mongodb会自动处理并发请求的调度。我是否只需要创建一个本地集群,或者将我当前的集群升级到更多连接?
发布于 2019-10-18 03:00:56
在这种情况下,典型的活动是创建输入queue.Queue并将任务放入其中,然后创建几个工作者来从队列中接收任务。如果您需要限制同时使用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.")https://stackoverflow.com/questions/58438448
复制相似问题