MongoDBPHPDriver connection Processing

Source: Internet
Author: User
Tags findone mongoclient mongodb driver mongodb server php mongodb
PHPMongoDBdriver of MongoDBPHPDriver 1.3 overwrites the connection processing database. Compared with previous versions, mongodbdriver has made significant changes in persistent connections and connection pools. Connection Pool is introduced to the driver of connection management of version 1.2. When any query is executed, a connection is requested from the connection pool and then returned.

MongoDB PHP Driver connection processing version 1.3 of PHP MongoDB driver overwrites the connection processing database. Compared with previous versions, there have been significant changes in persistent connections and connection pools. Connection Pool is introduced to the driver of connection management of version 1.2. When any query is executed, a connection is requested from the connection pool and then returned.

Connection handling of MongoDB PHP Driver

PHP MongoDB driver of version 1.3 overwrites the connection processing database. Compared with previous versions, it has made significant changes in persistent connections and connection pools.

1.2 connection management

The driver of version 1.2 introduces the connection pool. When any query is executed, a connection is requested from the connection pool and then returned to the connection pool. Completion means that the variable holding the connection leaves its scope. The following is an example.

The simplest version:


  Demo-> test; $ c-> insert (array ('test' => 'yes');?>

Disconnect $ m out of scope, connection returned to connection pool

In the function:


  Demo-> test; $ c-> insert (array ('test' => 'yes');} // disconnect $ m from the scope and return the connection to the connection pool?>

In some cases, the system may generate a large number of connections. For example, you can reference a connection object in a complex structure of ORMs/ODMs, as shown in the following example:


  

1.3 connection management

In version 1.3, connection management has been greatly changed. In each worker process (thread, PHP-FPM, or Apache worker), the driver separates the Connection Manager from the Mongo * object, reducing the complexity of the driver. The following uses a MongoDB instance of a single node to describe how the driver processes the connection.

When a worker process starts, the MongoDB driver initializes the Connection Manager Management connection for it, and no connection is established by default.

When the first request calls new clients client ();, the driver creates a new connection and identifies the connection with a hash value. The hash value includes the following parameters: Host Name, port, process ID, and optional replica set name. If it is a password-verified connection, the hash value of the Database Name, user name, and password is also included (for password verification connections, we will discuss in detail later ). Call the MongoClient: getConnections () method to view the hash value of the connection:


  getConnections()[0]['hash'] );?>

Output:

String (22) "whisky: 27017;-; X; 22835"

"-" In the output indicates that the connection does not belong to a certain replica set. "X" is a placeholder when no user name, database, or password is available. 22835 is the process ID of the current process.

Then the connection will be registered in the Connection Manager:

When a connection is required, including insertion, deletion, update, search, or execution of commands, the driver requests a suitable connection from the manager for execution. The new clients client () parameter and the ID of the current process are used to request a connection. Each worker process/thread and Connection Manager have a connection list, and each PHP worker runs only one request at the same time. Therefore, only one connection is required between each and every MongoDB and is continuously reused, until PHP worker terminates or explicitly calls closing client: close () to close the connection.

Replica sets

In an environment where a replica set exists, the situation is a bit different. In the connection string of new guest client (), you must specify multiple hosts and indicate that the current practical replica set is being used:

$ M = new MongoClient ("mongodb: // whisky: 13000, whisky: 13001 /? ReplicaSet = seta ");

The replicaSet parameter cannot be omitted. Otherwise, the driver considers that you are preparing to connect to three different mongos processes.

During instantiation, the driver checks the topology of the replica set. The output in the following example shows that after the new Consumer Client () is called, all visible data nodes in the replica set will register a connection in the Manager:


  getConnections() as $c ){    echo $c['hash'], "\n";}?>

Output:

Whisky: 13001; seta; X; 32315 whisky: 13000; seta; X; 32315

Although no whisky: 13000 node exists in the connection string, two connections have been registered in the Manager:

The manager not only contains the connected hash value and TCP/IP socket, but also stores which node is the master node and the "distance" of each node ". The following script displays the additional information;


  getConnections() as $c ){    echo $c['hash'], ":\n",        " - {$c['connection']['connection_type_desc']}, ",        "{$c['connection']['ping_ms']} ms\n";}?>

Output:

Whisky: 13001; seta; X; 5776:-SECONDARY, 1 mswhisky: 13000; seta; X; 5776:-PRIMARY, 0 MS

The driver divides operations into two types: write operations, including insert, update, delete, and command; read operations, including find and findOne. By default, if no read preference parameter is set, the Manager will always return the connection to the master node. The read preference parameter can be set through setSlaveOkay () or in the connection string:

$ M = new MongoClient ("mongodb: // whisky: 13000, whisky: 13001 /? ReplicaSet = seta & readPreference = secondaryPreferred ");

After these parameters are added, the connection string becomes very long. Therefore, the PHP driver allows options to be placed in an array and passed as the second parameter:

$options = array(        'replicaSet' => 'seta',        'readPreference' => 'secondaryPreferred',);$m = new MongoClient("mongodb://whisky:13000,whisky:13001/", $options);

For each operation, the driver requests an appropriate connection from the manager. For write operations, the connection to the master node is always returned. For read operations, if the secondary node is available and "not far from", the connection to the secondary node is returned.

Verified connection

If MongoDB enables the verification function, the connected hash value will contain the hash value related to the verification. In this way, different scripts can be used to connect different databases on the same MongoDB with different user names and passwords without misuse of connections. The following example uses the admin user name to connect to the admin database and observe the hash value changes:


  getConnections()[0]['hash'] );?>

Output:

String (64) "whisky: 27017;-; admin/bda5cc70cd5c23f7ffa1fda978ecbd30; 8697"

The "X" section in the previous example has been replaced with a Database Name admin, username admin, and hash value bda5cc70cd5c23f7ffa1fda978ecbd30. The hash value is calculated based on the user name, database name, and password hash value.

To verify that the database works correctly, you must include the database name in the connection string. Otherwise, the database name is admin by default.

To use a database after a connection is established, select the database first, for example:

$ Collection = $ m-> demoDb-> collection; $ collection-> findOne ();

If the selected database is the database specified in the connection string or the database in the connection string is admin, everything will run normally. Otherwise, the driver creates a new connection to prevent verification being bypassed, as shown below:


  test2;$collection = $db->collection;var_dump( $collection->findOne() );?>

Output:

Fatal error: Uncaught exception 'invalid cursorexception' with message 'whisky: 27017: unauthorized db: test2 ns: test2.collection lock type: 0 client: 127.0.0.1 'in... Mongo-connect-5.php.txt: 6

The connection fails because we did not perform authorization verification for the test2 database. If we perform the verification, it will run normally:


  test2;$db->authenticate('user2', 'user2' );$collection = $db->collection;$collection->findOne();foreach ( $m->getConnections() as $c ){    echo $c['hash'], "\n";}?>

Output:

Whisky: 27017;-; test/user/602b672e2fdcda7b58a042aeeb034376; 26983 whisky: 27017;-; test2/user2/984b6b4fd6c33f49b73f026f8b47c0de;

There are now two verified connections in the Manager:

By the way, if you open the E_DEPRECATED-Level Error prompt, you will see:

Deprecated: Function MongoDB: authenticate () is deprecated in... Mongo-connect-6.php.txt on line 5

It is recommended that the driver create two consumer client objects to complete this type of task:


   false ) );$mTest2 = new MongoClient( 'mongodb://user2:user2@whisky:27017/test2', array( 'connect' => false ) );$mTest1->test->test->findOne();$mTest2->test2->test->findOne();foreach ( $mTest2->getConnections() as $c ){    echo $c['hash'], "\n";}?>

The number of concurrent connections that a single MongoDB server can support is quite limited. If you use a PHP-FPM, each worker process has its own independent connection pool, it is easy to reach the upper limit of the number of connections. Therefore, in a production environment, mongos should be deployed, whether or not the replica set is used, and then the PHP-FPM is connected to mongos, which can reduce the number of connections to mongod, and short connections can be used between the PHP-FPM and mongos (that is, the close function is explicitly called at the end of each request to close the MongoDB connection ).

Link: http://derickrethans.nl/mongodb-connection-handling.html

Original article address: Connection handling for MongoDB PHP Driver. Thank you for sharing it with me.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.