设计思路
- 连接创建:初始化连接池时,创建一定数量的MongoDB连接对象,避免每次操作都新建连接。
- 连接管理:使用一个队列(Queue)来管理这些连接,线程需要连接时从队列获取,使用完毕后再放回队列。
- 连接复用:确保连接在放回队列后可以被其他线程复用,减少连接创建和销毁的开销。
- 异常处理:在获取和归还连接时,处理可能出现的异常情况,保证连接池的稳定性。
关键代码示例
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()