Database master-Slave setup _php tutorial

Source: Internet
Author: User
Tags zend framework
For some large-scale projects, we often use the database master-slave approach to read and write separation, to divert user operations, to achieve load balancing. So the online search for relevant information, do a summary. The following concepts are part of the encyclopedia or Web ppt, and the end of the code originates from this project.

First, because you have not done similar functions before, you need to understand conceptually:

Load Balancing
Load balancing: Load (work tasks) are balanced and distributed across multiple operating units to perform Balance tasks together. There are two main types of:
1. Cluster (clustering)
A single heavy load operation is divided into multiple nodes to do parallel processing, each node device processing end, the results are summarized, returned to the user, so that the system processing capacity has been greatly improved.
2. Diversion
A large amount of concurrent access or data traffic is distributed on multiple node devices, which reduces the time the user waits for a response, mainly for Web servers, FTP servers, enterprise-critical application servers, and other network applications. The master-slave architecture is this type of load balancing.

Benefits of master-slave architecture
1. Load balancing (read/write separation, improve data processing efficiency)
2. High availability and failover capabilities (data distribution, stability improvement. Primary server fails and can be supported from server)
3. Backup (cannot backup itself, but can provide a backup machine, easy to implement database disaster, backup, recovery, etc.)
4. Data consistency to avoid conflicts
5. Test MySQL Upgrade

MySQL replication feature
1: Support one master multi-slave mechanism. The data is replicated to the slave server through the master server.
2: Support multi-level structure. Master-Slave, from from, the main master (mutual main from).
3: Filtering is supported (you can copy only some of the data on the primary server, not all).

Types of replication
1. Statement-based replication: SQL statements executed on the primary server execute the same SQL statement from the server. MySQL uses statement-based replication by default and is more efficient.
2. Row-based replication: Copy the changed content past instead of executing the command on the server (mysql5.0 start support).
3. Mixed-type replication: statement-based replication is used by default. A row-based replication is used when a statement cannot be accurately copied based on the discovery
There are also three types of binary logs:
1:statement
2:row
3:mixed

Requirements for server architecture
1: Tables in the master-slave server can use different table types. In addition: a primary server with multiple slave servers at the same time, will affect its performance, can take out a server as a proxy from the server, using the Blockhole table type. Log only, do not write data, it takes more than one server, thereby improving performance.
2: Tables in the master-slave server can use different field types.
3: Tables in the master-slave server can use different indexes. Primary server is mainly used for write operations, so in addition to the primary key and unique index, such as the guarantee of data relationship index generally can not add, from the server is generally used for reading operations, so you can set the index for the query characteristics. Even: Different slave servers can set different indexes for different queries.

Replication process
The 1:master server changes records to binary log files, which are called Binary logging events (binary log event)
2:slave server copies the binary log events of Master to his trunk logs (relay log)
3:slave Redo the relay log event to reflect the change to its own data.

PHP Code implementation
1. server Connection Configuration file
If you have polymorphic Master | From the server, then just increment the number down.

[PHP]
[Database]
dbname = "vis_db"
CharSet = "UTF8"
; master
Servers.0.master = True
Servers.0.adapter = "Mysqli"
Servers.0.host = "vis_db"
Servers.0.username = "Vis"
Servers.0.password = "Vis"
; from
Servers.1.master = False
Servers.1.adapter = "Mysqli"
Servers.1.host = "Vis_mmc"
Servers.1.username = "Vis"
Servers.1.password = "Vis"

2. Database Operation Class Code
Determine the database on which server to connect, based on the user's IP redundancy.
The Zend Framework framework is used in the project.
[PHP]

/**
* Database Factory class
*
* @create 2012-05-29
* @note: This class is used to create zend_db_adapter instances of various configuration parameters
*/
Include_once ' lib/getrequestip.php ';

Class Free_db_factory
{

/**
* Zend_db_adapter Instance Array
*
* @var Array
*/
protected static $_dbs = Array ();

protected function __construct ($sName)
{
try {
$params = $this->_getdbconfig ($sName);
self::$_dbs[$sName] = zend_db::factory ($params [' Adapter '], $params);
} catch (Exception $e) {
if (DEBUG) {
echo $e->getmessage ();
}
Exit
}
}

/**
* Get Zend_db_adapter instances
* @return Zend_db_adapter
*/
public static function Getdb ($sName)
{
if (Emptyempty ($sName)) {
Exit
}

if (!isset (self::$_dbs[$sName])) {
New self ($sName);
}
return self::$_dbs[$sName];
}

/**
* Get the configuration of the database
*/
Private Function _getdbconfig ($sName)
{
$CONFIGARR = Array ();
$dbConfig = Zend_registry::get (' db ')->database->toarray ();
$serverConfigs = $dbConfig [' Servers '];
$masters = Array ();
$slaves = Array ();
foreach ($serverConfigs as $value) {
if (!isset ($value [' master ')]) {
Continue
}
if (true = = $value [' master ']) {
$masters [] = $value;
}
if (false = = $value [' master ']) {
$slaves [] = $value;
}
}
$masterNum = count ($masters);
$slaveNum = count ($slaves);

$requestIP = $this->_getrequestip ();

Switch ($sName) {
Case ' master ':
if ($masterNum > 1) {
$CONFIGARR = $masters [$requestIP% $masterNum];
} else {
$CONFIGARR = $masters [0];
}
Break
Case ' slave ':
if ($slaveNum > 1) {
$CONFIGARR = $slaves [$requestIP% $slaveNum];
} else {
$CONFIGARR = $slaves [0];
}
Break
Default:
Break
}
if (Emptyempty ($CONFIGARR)) {
return Array ();
}

$CONFIGARR [' dbname '] = $dbConfig [' dbname '];
$CONFIGARR [' charset '] = $dbConfig [' CharSet '];
return $CONFIGARR;
}

/**
* GET request IP
*/
Private Function _getrequestip ()
{
$ip = Getrequestip (true);
Return sprintf ('%u ', Ip2long ($IP));
} www.2cto.com

/**
* destructor Zend_db_adapter Entity (because some requests are time-consuming, this may cause the database to time out)
*/
public static function destructdb ($sName = null)
{
if (null = = = $sName) {
Self::$_dbs = null;
} else {
Unset (self::$_dbs[$sName]);
}
}

}
When calling code, pass in a flag that determines whether to manipulate the master or the database:
[PHP]
$oSlaveDb = Free_db_factory::getdb (' slave ');


Author: xinsheng2011

http://www.bkjia.com/PHPjc/478116.html www.bkjia.com true http://www.bkjia.com/PHPjc/478116.html techarticle for some large-scale projects, we often use the database master-slave approach to read and write separation, to divert user operations, to achieve load balancing. So the online search for the relevant letter ...

  • 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.