Brief Analysis of MongoDBphpdriver

Source: Internet
Author: User
Tags mongoclient mongodb driver php mongodb
Connection Pool, connection pool, persistent connection, and short connection pool. PHPMongoDBdriver version (1.2.0-1.2.12only) uses the connection pool (ConnectionPooling) 1.1.4 and earlier versions. You can choose to use a short connection or persistent connection. For example, write a program to connect to the database for 1000 times :? Phpfor ($ i0; $ I takes nearly 18 seconds;

Connection Pool, connection pool, persistent connection, and short connection pool. PHP MongoDB driver version (1.2.0-1.2.12 only) Connection Pool (Connection Pooling) 1.1.4 and earlier versions can be used to use short connections or persistent connections. For example, write a program to connect to the database for 1000 times :? Phpfor ($ I = 0; $ I takes nearly 18 seconds;

Connection Pool, persistent connection, and short connection
Connection Pool. PHP MongoDB driver version (1.2.0-1.2.12Only) Use the Connection pool (Connection Pooling)

1.1.4 and earlier versions can use short connections or persistent connections
For example, write a program to connect to the database for 1000 times:

 

It takes nearly 18 seconds;
Use persistent connections

  

Less than 0.02 seconds.

1.2.x uses the connection pool. All connections are persistent connections and the driver automatically manages them. The direct reason for using persistent connections is high efficiency. Connection reuse saves a lot of cost for creating connections. Persistent connections are maintained by PHP processes.
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.

After 1.3, the connection management was greatly changed, and the connection pool was abandoned. All connections were persistent connections.
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.
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,
For Password-verified connections, the hash values of database names, usernames, and passwords are also included (for password-verified connections, we will discuss them in detail later ).
Call the MongoClient: getConnections () method to view the hash value of the connection.
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,
Every PHP worker runs only one request at the same time. Therefore, only one connection is required between each PHP worker and MongoDB, which is continuously reused,
Until PHP worker terminates or explicitly calls closing client: close () to close the connection.

Source code brief analysis, version mongo-php-driver-1.4.5
Connection initialization and connection management
Connection manager initialization:
The Connection Manager is initialized in PHP_GINIT_FUNCTION () during module initialization.
Php_cmd.c L288 cmd_globals-> manager = cmd_init (); cmd_init () is defined in mcon/manager. c L622.
Mongo_init () initializes the establishment of a connection (socket connection ).

The Connection Manager is separated from the consumer client. The following describes the Consumer Client initialization:
Mongoclient. c L338

PHP_METHOD(MongoClient, __construct){ php_mongo_ctor(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);}

Php_mongo_ctor:
Specify the Connection Manager as the Global Manager above;
Parse some parameter settings of the connection, such as host, port, and option w,
Call the php_cmd_connect () function.
The php_cmd_connect () function is defined in Protocol client. c L275.
Php_pai_connect () mainly calls the functions of the pai_get_read_write_connection () (mcon/manager. c L415)
To obtain the appropriate connection;
Mongo_get_read_write_connection () is used to obtain a suitable connection:
Suitable connections are obtained based on standalone, replica set, mongos, and different read/write splitting settings.
Code correspondence
STANDALONE calls mongo_get_connection_multiple (defines mcon/manager. c L319)
REPLSET pai_get_read_write_connection_replicaset () (mcon/manager. c L249)
Multiple (the mongos type is processed here) pai_get_connection_multiple ()

Get connection and read/write splitting
Process the replicaSet option in mcon/parse. c L457
L483 sets servers-> options. con_type = pai_con_type_replset
The php_1__connect () function is called in _ construct () and connect () of the login client.
The php_cmd_connect () function is defined in Protocol client. c L275.
Call the mongo_get_read_write_connection () function in mongo_connection ().
The performance_get_read_write_connection () function is defined in mcon/manager. c L415.
Servers-> options. con_type is determined in pai_get_read_write_connection ().
For replica sets, call pai_get_read_write_connection_replicaset ()
Pai_get_read_write_connection_replicaset () is defined in mcon/manager. c L249.
In pai_get_read_write_connection_replicaset (), mongo_discover_topology () is called to detect the server.
Implementation of pai_discover_topology () in mcon/manager. c L144,
Pai_discover_topology ()-> pai_connection_ismaster (mcon/manager. c L167)
-> Bson_create_ismaster_packet (mcon/mini_bson.c L86)-> execute the isMaster command

Replica sets
Check the candidate servers according to the read preference settings.
Call performance_find_candidate_servers (mcon/read_preference.c L319)
Call performance_find_all_candidate_servers (mcon/read_preference.c L135)
PRIMARY find PRIMARY
PRIMARY_PREFERRED not processed
SECONDARY_PREFERRED: Find PRIMARY and SECONDARY.
SECONDARY: only SECONDARY
NEAREST for all types
Call pai_filter_candidates_by_replicaset_name (mcon/read_preference.c L211) and filter the data based on the replica set name;
Call pai_filter_candidates_by_credentials (mcon/read_preference.c L270) to authenticate the database, username, and password and add them to the candidate connection through verification.
Call the sort _sort_servers (mcon/read_preference.c L424) Sorting Algorithm Based on the read preference settings.
Call performance_select_nearest_servers (mcon/read_preference.c L461 ),
If read preference is set to PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED, NEAREST;
Select the member with the lowest ping value as the first element, and add the member with the lowest ping value within 15 ms.
Call cmd_pick_server_from_set (mcon/read_preference.c L510)
PRIMARY_PREFERRED,
Select the result based on the above sorting. if the first one is PRIMARY (usually), select PRIMARY,
(Of course, if the first one is not PRIMARY, that is, there is no master, enter the following random selection (rand (), and select a random replica integrator;
SECONDARY_PREFERRED,
Select the result according to the above sorting. If there are more than 1 members and if the last one is PRIMARY, select the members of SECONDARY except PRIMARY;
(If there is only one option, jump to the following random selection step and select PRIMARY)
Random selection, regardless of the read preference settings, including SECONDARY and nearest,
The difference between SECONDARY and nearest is that nearest treats PRIMARY as another secondaries.
Nearest does not select the one with the lowest ping value, but contains the combination with the lowest ping value in 15 ms (if there is more than one at this stage.

Mongos
Call cmd_get_connection_multiple (mcon/manager. c L319)
Call pai_get_connection_single (mcon/manager. c L55) to test connectivity
Call cmd_find_candidate_servers (mcon/read_preference.c L319)->
Call pai_filter_candidates_by_seed (mcon/read_preference.c L245) to generate a hash,
Compare the hash values in the seed list with those in servers, and return equal values.
Call pai_filter_candidates_by_credentials (mcon/read_preference.c L270) for authentication based on db, username, password
Verified connections are added to candidate connections.
Call the sort _sort_servers (mcon/read_preference.c L424) Sorting Algorithm Based on the read preference settings.
Ping time to sort.
Call pai_select_nearest_servers (mcon/read_preference.c L461) and select the lowest ping value.
Hash format:

  • HOST: PORT;-;.; PID
    Or
  • HOST: PORT; REPLSETNAME; DB/USERNAME/md5 (PID, PASSWORD, USERNAME); PID

Summary
Establish connections one by one for the given mongos connection strings to test connectivity. If none of them are connected, exit;
Filter and verify these connections, and select the fastest connection based on the ping value.
Therefore, for mongos, if only one connection is provided, other mongos cannot be found. This is different from replica sets,
For replica sets, any data member can find all other data members.

Refer:
Http://mongodb.github.io/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html
Http://emptysqua.re/blog/reading-from-mongodb-replica-sets-with-pymongo/
Http://docs.mongodb.org/manual/core/read-preference-mechanics/
Http://wulijun.github.io/2012/12/10/mongodb-php-driver-connectiong-handling.html
Http://derickrethans.nl/mongodb-connection-handling.html
Http://www.php.net/manual/zh/mongo.connecting.persistent.php

Original article address: Brief Analysis of 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.