MST

星途 面试题库

面试题:Python多线程下MongoDB连接池优化

在Python多线程环境中操作MongoDB,如何设计和实现一个高效的MongoDB连接池?请描述设计思路,并给出关键代码示例。
36.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 连接创建:初始化连接池时,创建一定数量的MongoDB连接对象,避免每次操作都新建连接。
  2. 连接管理:使用一个队列(Queue)来管理这些连接,线程需要连接时从队列获取,使用完毕后再放回队列。
  3. 连接复用:确保连接在放回队列后可以被其他线程复用,减少连接创建和销毁的开销。
  4. 异常处理:在获取和归还连接时,处理可能出现的异常情况,保证连接池的稳定性。

关键代码示例

import pymongo
from queue import Queue
from threading import Thread


class MongoConnectionPool:
    def __init__(self, host='localhost', port=27017, max_connections=5):
        self.host = host
        self.port = port
        self.max_connections = max_connections
        self.pool = Queue(maxsize=max_connections)
        for _ in range(max_connections):
            self.pool.put(pymongo.MongoClient(host, port))

    def get_connection(self):
        try:
            return self.pool.get(block=True, timeout=10)
        except Exception as e:
            print(f"获取连接失败: {e}")

    def return_connection(self, conn):
        try:
            self.pool.put(conn)
        except Exception as e:
            print(f"归还连接失败: {e}")


# 使用示例
def worker(pool):
    conn = pool.get_connection()
    if conn:
        db = conn['test_db']
        collection = db['test_collection']
        result = collection.find_one()
        print(result)
        pool.return_connection(conn)


if __name__ == "__main__":
    pool = MongoConnectionPool()
    threads = []
    for _ in range(3):
        t = Thread(target=worker, args=(pool,))
        threads.append(t)
        t.start()
    for t in threads:
        t.join()