连接池
mongocxx::client
vs mongocxx::pool
独立运行的mongocxx::client
使用单线程算法监控其所连接集群的状态。 当连接到副本集时,该线程每60秒“停止运行”,以检查集群的状态。 另一方面, mongocxx::pool
为集群中的每个服务器使用单独的后台线程,每个服务器每10秒检查一次其监控的服务器的状态。 由于在后台监控集群比“停止全局”监控集群具有性能优势,因此如果您的应用程序可以访问多个线程,则强烈建议使用mongocxx::pool
而不是一组独立的客户端,即使您的应用程序仅使用一个线程。
Using Threads with Connection Pools
mongocxx::pool
可以在多个线程之间共享,并用于创建客户端。 但是,每个mongocxx::client
只能在单个线程中使用。 有关如何以线程安全的方式使用mongocxx::client
的详细信息,请参阅线程安全文档。
Using Forks with Connection Pools
A mongocxx::pool
cannot be shared between a parent and a fork. You must create your connection pool after forking. See the fork safety documentation documentation.
配置连接池
The number of clients in a connection pool is limited by the URI parameter maxPoolSize
. After the number of clients created by a mongocxx::pool
(both in the pool and checked out) reaches the value of maxPoolSize
, mongocxx::pool::acquire
blocks until another thread returns a client to the pool. The default value is 100.
使用连接池
要使用连接池,请首先创建一个mongocxx::pool
,并将 URI 作为参数传递。 然后,调用mongocxx::pool::acquire
以从池中接收客户端。 当客户端超出范围时,将自动返回到池中。
有关更多详情,请参阅 连接池示例 。