Persistent Connections (version 1.3.0+)

All versions of the driver since 1.3.0 utilize persistent connections to minimize the number of connections made to each database server. These connections are saved by the PHP worker process and may be reused between multiple requests.

Before connecting to a database server, the driver will create a hash for the connection based on its host, port, replica set name (if any), any authentication credentials (e.g. username, password, database), and the process ID. If a connection already exists for that hash, it will be used in lieu of creating a new connection associated with that hash. MongoClient::getConnections() may be used to retrieve info about each persistent connection. Consider the following program:

<?php

$m1 
= new MongoClient('mongodb://localhost');
$m2 = new MongoClient('mongodb://localhost');
$m3 = new MongoClient('mongodb://user:pw@localhost');
$m4 = new MongoClient('mongodb://127.0.0.1');
$m5 = new MongoClient('mongodb://rs1.local:30017,rs2.local:30018/?replicaSet=rs');
$m6 = new MongoClient('mongodb://sharding.local:40017');

foreach (
MongoClient::getConnections() as $conn) {
    echo 
$conn['hash'], "\n";
}

?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

localhost:27017;-;X;15487
localhost:27017;-;admin/user/c56c…8bbc;15487
127.0.0.1:27017;-;X;15487
rs1.local:30017;rs;X;15487
rs2.local:30018;rs;X;15487
sharding.local:40017;-;X;15487

In this example $m1 and $m2 have the same hash and share a persistent connection. Connections for each other MongoClient instance hash to unique values and use their own sockets. Note that "localhost" and "127.0.0.1" do not share the same hash; DNS resolution is not taken into account.