与新 Mongo PHP 驱动程序的持久连接

Persistent connections with new Mongo PHP driver

对于一个项目,我将新的 MongoDB 驱动程序用于 PHP 和库(参见:https://docs.mongodb.com/php-library/master/),而不是旧驱动程序。

我们是 运行 PHP 7 作为 FPM。

我最近用 XDEBUG 做了一些分析,发现第一个数据库查询比第二个数据库查询慢得多,例如

Session::validate -> Account::find 38ms
getProfile        -> Account::find 2ms

其中 Account::find 将执行查询以通过其 _id 获取一个文档,并且两个调用查找不同的文档。

我的两个问题

  1. 据我所知,第一个查询比第二个查询慢得多,因为驱动程序必须与数据库服务器建立连接,在我们的例子中还必须进行身份验证。此连接不会在脚本执行之间持续存在。对吗?
  2. 如果 (1) 为真,是否有任何方法可以保持与新驱动程序的连接?据我了解,与数据库的旧驱动程序连接可以存储在请求之间。 (http://php.net/manual/de/mongo.connecting.persistent.php)

github 上有人将我指向 this 站点,所以我现在可以回答我自己的问题了。引用:

All versions of the driver since 1.2.0 persist the » libmongoc client object in the PHP worker process, which allows it to re-use database connections, authentication states, and topology information across multiple requests.

但是:

Versions of the PHP driver before 1.2.0 utilize PHP's Streams API for database connections, using an API within » libmongoc to designate custom handlers for socket communication; however, a new libmongoc client is created for each MongoDB\Driver\Manager. As a result, the driver persists individual database connections but not authentication state or topology information. This means that the driver needs to issue commands at the start of each request to authenticate and » discover the server topology.

由于在撰写本文时最新的稳定驱动程序版本为 1.1.9,因此不会保留身份验证信息。但是你可以升级到 1.2.0 alpha 版本,这可以大大加快连接过程,正如我在我的系统上的一些测试中发现的那样。目前 1.2.0 alpha 有一些已知的错误,所以我现在将坚持使用较慢的 1.1.9。

此回复很快就会过时...