Connection pooling vs persist connection mysqli

心已入冬 提交于 2019-12-05 02:47:21

Actually terms connection pooling and persistent connection refer to the same thing in case of mysqli in PHP.

Persistent connection in this case refers to MySQL connection open from PHP script which stays open after the script has finished executing, to be used again in some later executions.

Connection pooling means that there is a pool of persistent connections maintained by PHP. One idle connection from this pool is given to PHP script which wants to connect to MySQL and returned to pool when script finishes.

You might wonder why do we need the pool of MySQL connections at all, why don't we use just one persistent connection for all of the scripts?

There are two reasons for this:

  • PHP creates a pool of MySQL connections based on host/port/username/password used. If one script wants to connect to MySQL with some host/port/username/password combination, PHP searches for idle persistent connection which has the same values. If it's not found, then a new persistent connection is created with this host/port/username/password combination. So we need at least as many different persistent connection as there are different host/port/username/password values used by all of the scripts.
  • You cannot execute two SQL commands on one MySQL connection at the same time. This can happen when two PHP scripts are executing simultaneously. When two scripts want to communicate with MySQL at the same time, two persistent MySQL connections are created. Number of persistent connections in pool is equal to last number of maximum parallel PHP scripts executed, or equal to upper limit set in php.ini.

Important notice:

MySQL connection pools (and any other connection pools) can exist only if PHP is executing as a web server plugin. Pools do not work when it is working in fast-cgi mode or in any other way when PHP executable terminates after script execution.

Edit: MySQL connection pooling can be used in fast-cgi mode of PHP if web server is configured to reuse one PHP fast-cgi process for multiple requests. If PHP fast-cgi process is configured to exit after serving one request then all of it's MySQL connections are closed.

in libmysql18, it looks for any existing default mysql sock/port and tests it with the credentials. if it can't be found, the c++ function clone() is called, creating the new connection object(Resource). in certain cases this can result in a stack overflow. i'm not familiar with how it works in mysqlnd(native driver). maybe someone else is. if you want more information about how it works, install a version of facebooks HHVM-debug package and attempt to pass a connection via global in multiple nested functions. this can trigger a stack overflow under HHVM, which will show you every function called prior to the exception up to that point.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!