Home Backend Development PHP Tutorial Database master-slave settings_PHP tutorial

Database master-slave settings_PHP tutorial

Jul 13, 2016 pm 05:52 PM
by separation us database Way Compare of set up Views Read and write conduct use project

For some projects with relatively large access volume, we often use the database master-slave method to separate reading and writing to divert user operations and achieve load balancing. Therefore, I searched for relevant information online and made a summary. Some of the concepts below are taken from encyclopedias or online PPTs, and the codes at the end are from this project.

First of all, because I have never done a similar function before, I need to understand it conceptually:

Load Balancing
Load Balance: Balance and distribute the load (work tasks) to multiple operating units for execution, so as to complete the work tasks together. Mainly divided into two types:
1. Clustering
A single heavy-load operation is distributed to multiple node devices for parallel processing. After each node device completes processing, the results are summarized and returned to the user, greatly improving the system's processing capabilities.
2. Diversion
A large amount of concurrent access or data traffic is distributed to multiple node devices for separate processing, reducing the time users wait for responses. This is mainly targeted at network applications such as Web servers, FTP servers, and enterprise key application servers. The master-slave architecture is this type of load balancing.

Benefits of master-slave architecture
1. Load balancing (separation of reading and writing, improving data processing efficiency)
2. High availability and failover capabilities (data distribution, stability improvement. If the master server fails, the slave server can still be used for support)
3. Backup (it cannot back up itself, but it can provide a backup machine to facilitate disaster recovery, backup, recovery and other operations of the database)
4. Data consistency and avoid conflicts
5. Test Mysql upgrade

Mysql copy function
1: Supports one master and multiple slaves mechanism. Data is copied from the master server to the slave server.
2: Support multi-level structure. Master-slave, slave-slave, master-slave (mutually master-slave).
3: Support filtering function (you can copy only part of the data on the main server, not all).

Type of copy
1. Statement-based replication: a SQL statement executed on the master server, and the same SQL statement executed on the slave server. Mysql uses statement-based replication by default, which is more efficient.
2. Row-based replication: Copy the changed content instead of executing the command on the slave server (supported since mysql5.0).
3. Mixed type replication: Statement-based replication is adopted by default. When it is found that statement-based replication cannot be exact, row-based replication will be used
There are three corresponding binary logs:
1:STATEMENT
2:ROW
3: MIXED

Server structure requirements
1: Tables in the master-slave server can use different table types. In addition: a master server with multiple slave servers at the same time will affect its performance. You can use one server as a slave server proxy and use the BLOCKHOLE table type. It only records logs and does not write data. It drives multiple servers to improve performance.       
2: Tables in the master-slave server can use different field types.
3: Tables in the master-slave server can use different indexes. The master server is mainly used for write operations, so indexes that ensure data relationships, such as primary keys and unique indexes, generally do not need to be added; the slave server is generally used for read operations, so indexes can be set based on query characteristics. Even more: different slave servers can set different indexes for different queries.

Copy process
1: The master server records changes to the binary log file (binary log). These records are called binary log events (binary log events)
2: The slave server copies the master’s binary log events to his relay log
3: The slave redoes events in the relay log and reflects the changes to its own data.

PHP code implementation
1. Server connection configuration file
If there is a polymorphic master|slave server, then just increase the number downwards.

[php] 
[database] 
dbname                              = "vis_db" 
charset                             = "utf8" 
;主 
servers.0.master                    = true 
servers.0.adapter                   = "MYSQLI" 
servers.0.host                      = "vis_db" 
servers.0.username                  = "vis" 
servers.0.password                  = "vis" 
;从 
servers.1.master                    = false 
servers.1.adapter                   = "MYSQLI" 
servers.1.host                      = "vis_mmc" 
servers.1.username                  = "vis" 
servers.1.password                  = "vis" 

2. Database operation code
After taking the remainder based on the user IP, determine which database on the server to connect to.
Zend 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 instance
* @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 database configuration
​​*/
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
 
    /**
* Destruct Zend_Db_Adapter entity (because some requests are time-consuming, this period may cause the database to time out)
​​*/ 
    public static function destructDb($sName = null) 
    { 
        if (null === $sName) { 
            self::$_dbs = null; 
        } else { 
            unset(self::$_dbs[$sName]); 
        } 
    } 
 

调用代码时,传入一个标志,确定是操作主还是从数据库即可:
[php] 
$oSlaveDb = Free_Db_Factory::getDb('slave'); 


作者:xinsheng2011

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478116.htmlTechArticle对于一些访问量比较大的项目,我们常常采用数据库主从的方式进行读写分离,以分流用户操作,实现负载均衡。因此网上查找了相关的信...
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 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)

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to handle database connections and operations using C++? How to handle database connections and operations using C++? Jun 01, 2024 pm 07:24 PM

Use the DataAccessObjects (DAO) library in C++ to connect and operate the database, including establishing database connections, executing SQL queries, inserting new records and updating existing records. The specific steps are: 1. Include necessary library statements; 2. Open the database file; 3. Create a Recordset object to execute SQL queries or manipulate data; 4. Traverse the results or update records according to specific needs.

See all articles