Home Database Mysql Tutorial MongoDB php driver 简要分析

MongoDB php driver 简要分析

Jun 07, 2016 pm 04:34 PM
driver mongodb php about analyze connect

关于连接、连接池、长连接、短连接 连接池。PHP MongoDB driver 版本( 1.2.0-1.2.12 only )使用连接池(Connection Pooling) 1.1.4及之前版本可以选择使用短连接或者长连接 举个简单的例子,写段程序连接1000次数据库: ?phpfor ($i=0; $i 需要将近18秒; 使

关于连接、连接池、长连接、短连接
连接池。PHP MongoDB driver 版本( 1.2.0-1.2.12 only)使用连接池(Connection Pooling)

1.1.4及之前版本可以选择使用短连接或者长连接
举个简单的例子,写段程序连接1000次数据库:

<?php for ($i=0; $i
Copy after login

需要将近18秒;
使用长连接

<?php for ($i=0; $i "x"));
}
?>
Copy after login

小于0.02秒。

1.2.x 使用连接池,所有连接都是长连接,驱动自动管理。使用长连接的直接原因是效率高。因为连接复用而省去了大量的创建连接的开销。长连接由PHP进程维护。
在执行任何查询时,都会从连接池中请求一个连接,完成之后再归还给连接池。这里的完成是指持有该连接的变量离开了它的作用域。

1.3以后连接管理做了很大改动,抛弃了连接池,连接均为长连接。
每个worker进程(线程、PHP-FPM或Apache worker)中,驱动把连接管理和Mongo*对象分离,降低驱动的复杂度
当一个worker进程启动,MongoDB驱动会为之初始化连接管理器管理连接,并且默认没有连接。
在第一个请求调用new MongoClient();时,驱动创建一个新连接,并且以一个哈希值标识这个连接。
这个哈希值包括以下参数:主机名、端口,进程ID和可选的replica set名,
如果是密码验证的连接,则还包括数据库名、用户名和密码的哈希值(对于密码验证的连接,我们后面再详细讨论)。
调用MongoClient::getConnections()方法,可以查看连接对应的哈希值
然后该连接会在连接管理器中注册:
在需要连接的任何时候,包括插入、删除、更新、查找或执行命令,驱动都会向管理器请求一个合适的连接来执行。
请求连接时会用到new MongoClient()的参数和当前进程的ID。每个worker进程/线程,连接管理器都会有一个连接列表,
而每个PHP worker同一时刻,只会运行一个请求,因此和每个MongoDB之间只需要一个连接,不断重用,
直到PHP worker终止或显式调用MongoClient::close()关闭连接。

源码简要分析,版本mongo-php-driver-1.4.5
连接初始化及连接管理
连接管理器(manager)初始化:
模块初始化的时候也就是在PHP_GINIT_FUNCTION()里面,初始化连接管理器。
php_mongo.c L288 mongo_globals->manager = mongo_init(); mongo_init()定义在mcon/manager.c L622
mongo_init() 初始化建立连接(socket连接)。

连接管理器与MongoClient分离,下面看MongoClient初始化:
mongoclient.c L338

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

php_mongo_ctor主要工作:
指定连接管理器为上面的全局管理器;
解析连接的一些参数设置,如主机,端口,选项w等等,
调用php_mongo_connect()函数
php_mongo_connect()函数定义在mongoclient.c L275
php_mongo_connect()主要调用mongo_get_read_write_connection()函数(mcon/manager.c L415)
来获得合适的连接;
mongo_get_read_write_connection()主要工作是获得合适的连接:
根据单机、复制集、mongos以及不同读写分离设置获取到合适的连接
代码对应
STANDALONE 调用mongo_get_connection_multiple(定义mcon/manager.c L319)
REPLSET mongo_get_read_write_connection_replicaset()(mcon/manager.c L249)
multiple(mongos类型在这里处理) mongo_get_connection_multiple()

获取连接及读写分离
在mcon/parse.c L457 处理replicaSet选项
L483 设置了servers->options.con_type = MONGO_CON_TYPE_REPLSET
MongoClient的__construct()和connect()里面会调用php_mongo_connect()函数
php_mongo_connect()函数定义在mongoclient.c L275
在mongo_connection()里面调用mongo_get_read_write_connection()函数
mongo_get_read_write_connection()函数定义在mcon/manager.c L415
在mongo_get_read_write_connection()里面判断了servers->options.con_type
对于replica sets,调用mongo_get_read_write_connection_replicaset()
mongo_get_read_write_connection_replicaset()定义在mcon/manager.c L249
在mongo_get_read_write_connection_replicaset()里面调用了mongo_discover_topology()去探测服务器
mongo_discover_topology()的实现在mcon/manager.c L144 ,
mongo_discover_topology()->mongo_connection_ismaster(mcon/manager.c L167)
->bson_create_ismaster_packet(mcon/mini_bson.c L86)->执行isMaster命令

replica sets
根据read preference设置,查出候选servers.
调用mongo_find_candidate_servers(mcon/read_preference.c L319)
调用mongo_find_all_candidate_servers (mcon/read_preference.c L135)
PRIMARY 找PRIMARY
PRIMARY_PREFERRED 不处理
SECONDARY_PREFERRED 找PRIMARY和SECONDARY
SECONDARY 只找SECONDARY
NEAREST 找所有类型
调用mongo_filter_candidates_by_replicaset_name(mcon/read_preference.c L211),根据复制集名称过滤;
调用mongo_filter_candidates_by_credentials (mcon/read_preference.c L270) 根据db,username,password认证,通过验证的添加到候选连接里。
调用mongo_sort_servers (mcon/read_preference.c L424)根据read preference的几种设置选项对于的排序算法,基本都是按照 ping time来排序。
调用mongo_select_nearest_servers(mcon/read_preference.c L461),
如果read preference设置的是PRIMARY,PRIMARY_PREFERRED,SECONDARY,SECONDARY_PREFERRED,NEAREST;
选择ping值最低的作为第一个元素,距最低的ping值15ms内的成员都添加进去。
调用mongo_pick_server_from_set (mcon/read_preference.c L510)
PRIMARY_PREFERRED,
根据上面的排序选择结果,如果第一个是PRIMARY(一般是),选择PRIMARY,
(当然选择如果第一个不是PRIMARY,即无主的情况,进入下面的随机选择(rand()),随机选一个复制集成员;
SECONDARY_PREFERRED,
根据上面的排序选择结果,如果大于1个,如果最后一个是PRIMARY,随机选择除PRIMARY之外SECONDARY的成员;
(当然如果只有1个了,跳到下面的随机选择步骤,选择的是PRIMARY)
随机选择,这里不管read preference设置,包含SECONDARY和nearest,
SECONDARY和nearest区别是nearest把PRIMARY当做其他secondaries一样。
nearest不是选择ping值绝对最低的那一个,而是包含绝对最低的+15ms内的组合里(如果到这个阶段不止一个的话)随机选择一个。

mongos
调用mongo_get_connection_multiple(mcon/manager.c L319)
调用mongo_get_connection_single( mcon/manager.c L55),测试连通性
调用mongo_find_candidate_servers (mcon/read_preference.c L319)->
调用mongo_filter_candidates_by_seed ( mcon/read_preference.c L245 ) 连接生成hash,
比较seed列表里hash与servers里的hash,返回相等的。
调用mongo_filter_candidates_by_credentials (mcon/read_preference.c L270) 根据db,username,password认证
通过验证的添加到候选连接里。
调用mongo_sort_servers (mcon/read_preference.c L424)根据read preference的几种设置选项对于的排序算法,基本都是按照
ping time来排序。
调用mongo_select_nearest_servers(mcon/read_preference.c L461),选择ping值最低的。
Hash格式:

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

简单总结
对给出的mongos连接串,逐个去建立连接,测试连通性,如果都连不通,退出;
对这些连接做一下过滤与验证,对合格的连接根据ping值选择最快的来连接。
所以对于mongos来说,如果只提供一个连接,是不能找到其他mongos的。这与replica sets不同,
对于replica sets,任意一个数据成员可以找到其他所有数据成员。

参考:
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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles