search
HomeBackend DevelopmentPHP TutorialDatabase master-slave settings_PHP tutorial

Database master-slave settings_PHP tutorial

Jul 13, 2016 pm 05:52 PM
byseparationusdatabaseWayCompareofset upViewsRead and writeconductuseproject

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
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),