Overview
このガイドでは、 PyMongo が接続プールを使用してMongoDBデプロイへの接続を管理する方法と、アプリケーションで接続プール設定を構成する方法について学習できます。
接続プール とはオープンデータベース接続のキャッシュであり、 PyMongoによって維持されます。 アプリケーションがMongoDBへの接続を要求すると、 PyMongo はプールからシームレスに接続を取得し、操作を実行し、再利用するためにプールに接続を返します。
接続プールは、アプリケーションのレイテンシと新しい接続がPyMongoによって作成される回数を削減するのに役立ちます。
接続プールの構成
次の接続プール設定は、MongoClientオブジェクトまたは接続 URI で指定できます。
設定 | 説明 |
|---|---|
| The time that PyMongo waits when establishing a new
connection before timing out. Data Type: intDefault: 20000MongoClient Example: connectTimeoutMS = 40000Connection URI Example: connectTimeoutMS=40000 |
| The maximum number of connections that each pool can establish concurrently.
If this limit is reached, further requests wait until a connection is established
or another in-use connection is checked back into the pool. Data Type: intDefault: 2MongoClient Example: maxConnecting = 3Connection URI Example: maxConnecting=3 |
| The maximum time that a connection can remain idle in the pool. When a connection
exceeds this limit, PyMongo closes the connection and removes it from
the pool. Data Type: intDefault: None (no limit)MongoClient Example: maxIdleTimeMS = 60000Connection URI Example: maxIdleTimeMS=60000 |
| The maximum number of concurrent connections that the pool maintains.
If the maximum pool size is reached, further requests wait until a connection
becomes available. Data Type: intDefault: 100MongoClient Example: maxPoolSize = 150Connection URI Example: maxPoolSize=150 |
| The minimum number of concurrent connections that the pool maintains. If
the number of open connections falls below this value due to network errors,
PyMongo attempts to create new connections to maintain this minimum. Data Type: intDefault: 0MongoClient Example: minPoolSize = 3Connection URI Example: minPoolSize=3 |
| The length of time that PyMongo waits for a response from the server
before timing out. Data Type: intDefault: None (no timeout)MongoClient Example: socketTimeoutMS = 100000Connection URI Example: socketTimeoutMS=100000 |
| How long a thread waits for a connection to become available in the connection pool
before timing out. Data Type: intDefault: None (no timeout)MongoClient Example: waitQueueTimeoutMS = 100000Connection URI Example: waitQueueTimeoutMS=100000 |
次のコードでは、maxPoolSize パラメータを使用して最大接続プールサイズが 50 のクライアントを作成します。対応するコードを表示するには、Synchronous タブまたは Asynchronousタブを選択します。
client = MongoClient(host, port, maxPoolSize=50)
client = AsyncMongoClient(host, port, maxPoolSize=50)
次のコードでは、前の例と同じ構成のクライアントを作成しますが、接続 URI を使用します。
client = MongoClient(host, port, maxPoolSize=50)
client = AsyncMongoClient(host, port, maxPoolSize=50)
詳細情報
接続プールの詳細については、 MongoDB Serverマニュアルの「 接続プールの概要」を参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。