PHP Connection Pool Detailed

Source: Internet
Author: User
Tags apc connection pooling dbase ibm db2 pconnect php class sapi sybase
PHP script itself does not do the connection pool, because the PHP script will release all memory resources after the completion of the interpretation, of course, the use of the database connection will be freed, but some middleware can also be used as a connection pool, as long as the relevant driver to provide PHP, so you can do the PHP connection pool, But definitely not the 100% pure PHP connection pool. Mysql_pconnect is a built-in analog connection pool in PHP, but this mechanism is not implemented in PHP scripts. But a single request can be reused to reduce the cost of new.

  1. <?php class Connectodb {private static $instance =array ();                   Prevent external creation of a new database connection class private function _constuct () {} static public function Connect () { Connection class Not enough 100, create a new class if (Count (self:: $instance) <100) {$newDb-=new self                   ();                   Self:: $instance []= $newDb;               Return $newDb:: Condb ();                   } else {//random number guarantees database connection equalization $i =rand (0,99);                   $new _obj=self:: $instance [$i];               return $new _obj::condb (); }} static Private Function condb () {try {$c                   Onnec=mysql_connect ("127.0.0.1", "Database Account", "Database Password");                   mysql_select_db ("database name");//Select Database} catch (Exception $e) { $errors []= $e->getmessage ();                }} 

The main purpose of connection pooling is to save time to open the database. The connection pooling mechanism saves time by pre-opening n database connections, caching them, and using these open connections directly when the database needs to be used. The presence of a connection pool basically eliminates the time and CPU overhead of database connection disconnection.
Connection Pooling Solution:
1, Pconnect (persistent connection): the principle of pconnect, and the connection pool is similar, is the program to close the connection, but PHP is not really shut down, when opened again, directly using the available connection.
MySQL should configure the value of Max_connection in the my.cnf of the MySQL database service, such as Max_connections = 2000, if the traffic is too large to appear.
2, MySQL proxy.
3. Memcache: A database cache implementation for MySQL.
4, SQL Relay: An open source database pool connection Proxy server. Supports Oracle, MySQL, MSQL, PostgreSQL, Sybase, MS SQL Server, IBM DB2, Sybase, SQLite, Lago, ODBC, MS Access, and more.
Installing and Configuring SQL SERVER (http://blog.sina.com.cn/s/blog_4dd475390100hbck.html), installing SQL Relay requires installing Rudiments first:
1, Installation rudiments:
# tar Vxzf rudiments-0.28.2.tar.gz
# CD rudiments-0.28.2
#./configure--prefix=/usr/local/rudiments
# make
# make Install
2. Install SQL Relay:
# tar Vxzf sqlrelay-0.36.4.tar.gz
# CD sqlrelay-0.36.4
#./configure--prefix=/usr/local/sqlrelay--with-rudiments-prefix=/usr/local/rudiments--with-mysql-prefix= MySQL installation path--with-freetds-prefix=freetds installation path--with-oracle-home=oracle installation path--with-php-prefix=php installation path
# make
# make Install
3, set PHP: Modify php.ini in Extension_dir = "./", modify the above content to: Extension_dir = "/usr/local/php/lib/php/extensions/ no-debug-non-zts-20050922 ".
According to the PHP installation path to modify, not every version of PHP is this path, in php.ini add the following content extension=sql_relay.so.
4. Modify the SQL Relay configuration file
# CD/USR/LOCAL/SQLRELAY/ETC
# CP Sqlrelay.conf.example sqlrelay.conf
Change the contents of sqlrelay.conf to:

<?xml version= "1.0"? ><! DOCTYPE instances SYSTEM "SQLRELAY.DTD" ><instances><instance id= "msdetest" port= "9000" socket= "/tmp/ Msdetest.socket "dbase=" FreeTDS "connections=" 5 "maxconnections=" maxqueuelength= "0" growby= "1" ttl= "60" Endofsession= "Commit" sessiontimeout= "5" runasuser= "Nobody" runasgroup= "Nobody" cursors= "5" authtier= "Listener" handoff= "Pass" ><users><user user= "sa" password= "sa"/></users><connections>< Connection connectionid= "Msdetest" string= "SERVER=MSDE;DB=PUBS;USER=SA;PASSWORD=SA;" metric= "1"/></ Connections></instance></instances>

Start SQL Relay, and test;
1. Start SQL Relay
# Export path= $PATH:/usr/local/sqlrelay/bin
# Sqlr-start-id Msdetest
2. Using SQL Tools:
# Sqlrsh-id Msdetest
You can enter SQL statements directly to stop SQL relay:# sqlr-stop msdetest
3, test php, write a php file, the content is as follows:

<? $con =sqlrcon_alloc ("Msdetest", 9000, "/tmp/msdetest.socket", "sa", "sa", 0,1), $cur =sqlrcur_alloc ($con); sqlrcur _sendquery ($cur, "select * from T_gifts"), for ($row =0; $row <sqlrcur_rowcount ($cur); $row + +) {for ($col =0; $col < Sqlrcur_colcount ($cur); $col + +) {echo Sqlrcur_getfield ($cur, $row, $col); echo ",";} echo "<br>\n";} Sqlrcur_free ($cur); Sqlrcon_free ($con);? >


Php+sqlrelay+mysql for connection pooling and read-write load balancing:
to effectively address the bottleneck of concurrent access, Use multiple database Master-slave mode to increase the amount of concurrent access to the Web. The Master-slave mode is for data synchronization issues. The
Sqlrelay solves the connection pooling problem and the balanced load that enables read-write separation. Sqlrelay Configuration 3 Instance A/b/c,a is responsible for reading data from master and slave, B is responsible for writing data, and only write Master,c is responsible for dispatching the application router. PHP connects the database through a or through B. In the actual configuration, because master assumes the read and write operation, then in instance A's configuration, the connection from master can be reduced slightly, the number of connections from the slave connection to read the data slightly increased to balance.
Configuration and Application (http://blog.163.com/lgh_2002/blog/static/4401752620107393057989/):

One, MySQL master/slave configuration
################
#mster/slave configuration
################
master:192.168.1.51
slave:192.168.1.50
1, master configuration
/etc/my.cnf add
Binlog-do-db=book book to the database name to ensure
Server-id=1
Log-bin=mysql-bin
Authorizing a copy operation to a rep user
GRANT REPLICATION SLAVE on book.* to rep@192.168.1.50 Identified by ' 123456 ';
Restart the master Service
2, configure slave
vi/etc/my.cnf
settings below 4 lines
Server-id = 2
Master-host = 192.168.1.51
Master-user = Rep
Master-password = 123456
Restart slave
3, import the raw data from master to slave.


Two, sqlrelay configuration
The most popular connection pool solution in the current industry is almost no support for PHP, After a lot of efforts finally found an open source connection pool technology--------Sqlrelay.
Sqlreplay Supported languages: C C + + Perl Python PHP Ruby Java TCL Zope.
Sqlreplay Supported databases: Oracle MySQL mSQL PostgreSQL sybase MS SQL Server IBM DB2 Interbase Sybase SQLite ODBC Ms Access
Basic Idea:
1, configure 2 instances for final processing of business
Clubs-read
Clubi-write
Where the read instance is configured with two connections respectively, and two connections start the peer connection number.
2, configure a instance to dispatch read and write operations, that is, CLUBR
through router to distinguish between read and write connection to different MySQL database.

<?xml version= "1.0"? ><! DOCTYPE instances SYSTEM "SQLRELAY.DTD" ><instances><!--club Instance--><instance id= "clubs" port= " 9002 "socket="/tmp/clubs.socket "dbase=" MySQL "connections=" "maxconnections=" "maxqueuelength=" 5 "growby=" 1 "ttl = "endofsession=" "Commit" sessiontimeout= "runasuser=" Nobody "runasgroup=" Nobody "cursors=" 5 "authtier=" Listener "handoff=" pass "deniedips=" "allowedips=" "debug=" None "Maxquerysize=" 65536 "maxstringbindvaluelength=" 4000 "Maxlobbindvaluelength=" 71680 "idleclienttimeout="-1 "maxlisteners="-1 "listenertimeout=" 0 "><users>< User user= "Club" password= "Edb:club"/></users><connections><connection connectionid= "Master51" String= "Host=192.168.1.51;port=3306;db=book;user=club;password=club;" metric= "1" behindloadbalancer= "no"/> <connection connectionid= "Slave50" string= "Host=192.168.1.50;port=3306;db=book;user=club;password=club;" metric= "1" behindloadbalancer= "no"/></connections></Instance><instance id= "Clubi" port= "9003" socket= "/tmp/clubi.socket" dbase= "MySQL" connections= "10" Maxconnections= "maxqueuelength=" 5 "growby=" 1 "ttl=" endofsession= "" Commit "sessiontimeout=" runasuser= " Nobody "runasgroup=" Nobody "cursors=" 5 "authtier=" Listener "handoff=" pass "deniedips=" "allowedips=" "debug=" None " Maxquerysize= "65536" maxstringbindvaluelength= "4000" maxlobbindvaluelength= "71680" idleclienttimeout= "-1" maxlisteners= "-1" listenertimeout= "0" ><users><user user= "club" password= "Edb:club"/></users> <connections><connection connectionid= "master51" string= "host=192.168.1.51;port=3306;db=book;user=club; Password=club; "metric=" 1 "behindloadbalancer=" no "/></connections></instance>

php.ini file priority in the system: Phpinidir, registry key, environment variable%phprc%, PHP5 root directory (for CLI), or www root directory (for SAPI moudles), Windows directory (C:\windows).
PHP5 Features: The object-oriented mechanism, complex processing of XML and exception handling mechanism are added.
PHP6 Features:
Unicode support: Although Unicode occupies more space, the convenience of Unicode is far more than the disadvantage of occupying space. PHP can also set whether support Unicode is turned on in the. ini file.
Namespaces: Namespaces are a way to avoid naming conflicts between functions or classes, and to make your functions and classes and methods unreadable without using prefix naming conventions.
PHP6.0 is an exciting Web 2.0 feature.
SOAP: The Simple Object Access Protocol (Soap:simple object, Access Protocol) soap can be used in conjunction with many existing Internet protocols and formats, including HTTP, SMTP, MIME, RPC.
XML: Starting with PHP version 5.1, XmlReader and XmlWriter are already included in the PHP kernel, which allows it to make XML programming easier.
Register Globals will be removed: it is full of convenience, but ignores the hidden dangers of procedural security, when the php4.3.x version starts, this default setting value is OFF, PHP6 PHP3 will not be used at all.
Magic Quotes will disappear: The Magic Quotes mainly automatically escapes the characters that need to be escaped, and this feature removes the leaf in line with the voice of most PHP developers.
Safe Mode is canceled.
The ' var ' Alias is ' public ': the Var declaration in the class becomes the alias of public and is believed to be a decision for compatibility with PHP5, and PHP6 can now be called as OO language.
Returning by reference will make an error: Now the compiler will be returned with a reference, such as $ A =& new B (), function &c (), the OO language default is reference, so no need to use &.
Zend.ze1 compatbility mode will be removed ZEND.ZE1 compatibility mode will be removed PHP5 is for compatibility with old PHP4, so you can choose whether to turn on compatibility mode in. ini.
Freetype 1 and GD 1 support will not see these two is a long time libs, so no longer supported, GD1 has already been replaced by the GD2 now.
DL () was moved to SAPI in DL () mainly for the designer to load extension Libs, which is now moved to SAPI.
Register Long Array removal from PHP5 By default is off, then PHP6 officially removed.
Extension changes: such as XmlReader, XmlWriter will no longer appear in the extension way, they will be moved into the core of PHP is turned on by default.
Ereg extension will be put into pecl, which means it will be removed from the PHP core, which is also to give way to the new regular expression extension, in addition, Fileinfo extension will be imported into the core of PHP.
APC will be imported into the core: This is a feature that improves PHP performance, and now it will be placed in the PHP core, and you can choose whether to enable APC.
Say goodbye to the ASP-style start tag: It's no longer necessary to please the ASP developer to use PHP.
PHP6.0 in addition to adding new features, some features that will bring instability and security risks to the system will also be canceled, with the list: Magic_quotes, Register_globals, Register_long_arrays, Safe_mode, Magic_quotes.

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.