In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to deal with the PHP MongoDB drive1.2 version connection and how to deal with the PHP MongoDB drive1.3 version, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
Version 1.3 of PHPMongoDBdriver rewrites the connection handling library, and there are significant changes in persistent connections and connection pooling compared to previous versions.
How to deal with the connection of PHPMongoDBdrive1.2 version
Version 1.2 of the driver introduces connection pooling, which requests a connection from the connection pool when any query is executed and returns it to the connection pool when it is complete. The completion here means that the variable holding the connection is out of its scope, and here is an example.
The simplest version:
$m=newMongoClient (); / / ← requests a connection from the connection pool
$cantilever-> demo- > test
C-> insert (array ('test'= >' yes'))
>
← $m leaves scope and the connection is returned to the connection pool
In the function:
FunctiondoQuery ()
{
$m=newMongoClient (); / / ← requests a connection from the connection pool
$cantilever-> demo- > test
C-> insert (array ('test'= >' yes'))
} / / ← $m leaves scope and the connection is returned to the connection pool
>
In some cases, the system may produce a large number of connections, such as referencing connection objects in a complex structure of ORMs/ODMs, as shown in the following example:
For ($iSuppli
What about the PHPMongoDBdrive1.3 version?
In version 1.3, connection management has changed a lot. In each worker process (thread, PHP-FPM, or Apacheworker), the driver separates the connection management from the Mongo* object, reducing the complexity of the driver. The following example shows how the driver handles connections with an MongoDB instance of a single node.
When a worker process starts, the MongoDB driver initializes the connection manager management connection for it, and there is no connection by default.
When newMongoClient (); is called on the first request, the driver creates a new connection and identifies the connection with a hash. This hash value includes the following parameters: hostname, port, process ID, and optional replicaset name, and if it is a password-authenticated connection, it also includes the database name, user name, and password hash value (for password-authenticated connections, we will discuss in more detail later). Call the MongoClient::getConnections () method to view the hash value corresponding to the connection:
$m=newMongoClient ('mongodb://whisky:27017/')
Var_dump ($m-> getConnections () [0] ['hash'])
>
Output:
String (22) "whisky:27017;-;X;22835"
The "-" in the output indicates that the connection does not belong to a replicaset, "X" is a placeholder without a user name, database, and password, and 22835 is the process ID of the current process.
The connection is then registered in the connection manager:
Whenever a connection is needed, including insert, delete, update, find, or execute commands, the driver requests an appropriate connection from the manager to execute. The parameter of newMongoClient () and the ID of the current process are used when requesting a connection. For every worker process / thread, the connection manager has a list of connections, and each PHPworker runs only one request at the same time, so only one connection is needed with each MongoDB and is reused until the PHPworker terminates or explicitly calls MongoClient::close () to close the connection.
Replicasets
In an environment where replication sets exist, the situation is a little different. In the connection string of newMongoClient (), you need to specify more than one hosts and indicate that the replication set is currently being applied:
$m=newMongoClient ("mongodb://whisky:13000,whisky:13001/replicaSet=seta")
The replicaSet parameter cannot be omitted, otherwise the driver will assume that you are ready to connect three different mongos processes.
When instantiated, the driver checks the topology of the replication set. The output of the following example shows that after calling newMongoClient (), all visible data nodes in the replication set register a connection in the manager:
$m=newMongoClient ('mongodb://whisky:13001/replicaSet=seta')
Foreach ($m-> getConnections () as$c)
{
Echo$c ['hash'], "\ n"
}
>
Output:
Whisky:13001;seta;X;32315whisky:13000;seta;X;32315
Although there are no whisky:13000 nodes in the connection string, two connections have been registered in the manager:
The manager contains not only the hash value and TCP/IPsocket of the connection, but also which node is the primary node and the "distance" of each node. The following script shows this additional information
$m=newMongoClient ('mongodb://whisky:13001/replicaSet=seta')
Foreach ($m-> 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,1mswhisky:13000;seta;X;5776:-PRIMARY,0ms
Drivers divide operations into two types: write operations, including insert, update, delete, and commands, and read operations, including find and findOne. By default, if the read preference parameter is not set, the manager will always return the connection to the primary node. The read preference parameter can be set either through setSlaveOkay () or in the connection string:
$m=newMongoClient ("mongodb://whisky:13000,whisky:13001/replicaSet=seta&readPreference=secondaryPreferred")
With these parameters added, the connection string becomes very long, so the PHP driver allows you to put options in an array and pass in as the second parameter:
$options=array (
'replicaSet'= >' seta'
'readPreference'= >' secondaryPreferred'
)
$m=newMongoClient ("mongodb://whisky:13000,whisky:13001/", $options)
For each operation, the driver requests a suitable connection from the manager. For write operations, the connection to the primary node is always returned; for read operations, the connection to the secondary node is returned if the secondary node is available and "not far" away.
Verified connection
If MongoDB enables authentication, the hash value of the connection will contain the hash value associated with validation. In this way, when different scripts connect to different databases on the same MongoDB with different user names and passwords, they can distinguish from each other without misusing the connection. The following example uses the admin user name to connect to the admin database, and then observe the change in the hash value:
$m=newMongoClient ('mongodb://admin:admin@whisky:27017/admin')
Var_dump ($m-> getConnections () [0] ['hash'])
>
Output:
String (64) "whisky:27017;-;admin/admin/bda5cc70cd5c23f7ffa1fda978ecbD30;8697"
The "X" section of the previous example has been replaced with one containing the database name admin, user name admin, and hash value bda5cc70cd5c23f7ffa1fda978ecbd30, which is calculated based on the user name, database name, and password hash value.
To verify that it works correctly, you need to include the database name in the connection string, otherwise it will default to admin.
To use the database after establishing a connection, you need to select the database first, such as:
$collection=$m- > demoDb- > collection;$collection- > findOne ()
If the selected database is the database specified in the connection string, or if the database in the connection string is admin, everything will work fine. Otherwise, the driver creates a new connection to prevent authentication from being bypassed, as shown below:
$m=newMongoClient ('mongodb://user:user@whisky:27017/test')
$db=$m- > test2
$collection=$db- > collection
Var_dump ($collection- > findOne ())
>
Output:
Fatalerror:Uncaughtexception'MongoCursorException'withmessage'whisky:27017:unauthorizeddb:test2ns:test2.collectionlocktype:0client:127.0.0.1'in... / mongo-connect-5.php.txt:6
Because our connection did not perform authorization verification for the test2 database, it failed. If we perform validation, it will work properly:
$m=newMongoClient ('mongodb://user:user@whisky:27017/test')
$db=$m- > 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;26983whisky:27017;-;test2/user2/984b6b4fd6c33f49b73f026f8b47c0de;26983
There are now two authenticated connections in the manager:
By the way, if you turn on the error message at the E_DEPRECATED level, you will see:
Deprecated:FunctionMongoDB::authenticate () isdeprecatedin... / mongo-connect-6.php.txtonline5
The driver recommends that you accomplish this task by creating two MongoClient objects:
$mTest1=newMongoClient ('mongodb://user:user@whisky:27017/test',array (' connect'= > false))
$mTest2=newMongoClient ('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, and if you use PHP-FPM, each worker process has its own independent connection pool, so it is easy to reach the upper limit of the number of connections. Therefore, in a production environment, mongos is deployed with or without replication sets, and then PHP-FPM connects to mongos, which reduces the number of connections to mongod, and short connections can be used between PHP-FPM and mongos (that is, the close function is explicitly called at the end of each request to close the MongoDB connection).
This is the answer to the question about how to deal with the connection of the PHP MongoDB drive1.2 version and how to deal with the PHP MongoDB drive1.3 version. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.