【问题标题】:MongoDB M0 cluster, python multithreadingMongoDB M0 集群,python 多线程
【发布时间】:2020-02-14 17:14:53
【问题描述】:

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

Connections % of configured limit has gone above 80

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

【问题讨论】:

  • 我试图通过在客户端的初始化中添加一个最大池大小关键字 arg 来解决这个问题,但这不起作用。我希望能够做到这一点,而不必为传入的请求实现我自己的锁。我可以做手动解决方案,但这很愚蠢,因为我认为我应该能够完成这个小任务。还要进一步说明,在 python 中我得到以下错误:indexerror : deque is empty

标签: python mongodb multithreading pymongo


【解决方案1】:

案例中的典型活动是创建输入 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.")

【讨论】:

  • 谢谢你,我什至没有想过将线程集中到工作组中!
猜你喜欢
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
相关资源
最近更新 更多