


Detailed explanation of read and write separation of MySQL database under thinkphp
This article mainly introduces the analysis of the read-write separation code of the MySQL database under thinkphp. It has certain reference value. Interested friends can refer to it.
When using the original SQL statement for write operations, execute is used, and query is used for read operations.
MySQL data master-slave synchronization still relies on the MySQL mechanism, so the delay problem of MySQL master-slave synchronization needs to be optimized at this time. If the delay time is too long, it not only affects the business, but also affects the user experience.
In the thinkphp core class Thinkphp/library/Model.class.php, the query method calls Thinkphp/library/Think/Db/Driver/Mysql.class.php
/** * SQL查询 * @access public * @param string $sql SQL * @param mixed $parse 是否需要解析SQL * @return mixed */ public function query($sql,$parse=false) { if(!is_bool($parse) && !is_array($parse)) { $parse = func_get_args(); array_shift($parse); } $sql = $this->parseSql($sql,$parse); return $this->db->query($sql); }
Call Thinkphp/library/Think/Db/Driver/Mysql.class.php
/** * 执行查询 返回数据集 * @access public * @param string $str sql指令 * @return mixed */ public function query($str) { if(0===stripos($str, 'call')){ // 存储过程查询支持 $this->close(); $this->connected = false; } $this->initConnect(false); if ( !$this->_linkID ) return false; $this->queryStr = $str; //释放前次的查询结果 if ( $this->queryID ) { $this->free(); } N('db_query',1); // 记录开始执行时间 G('queryStartTime'); $this->queryID = mysql_query($str, $this->_linkID); $this->debug(); if ( false === $this->queryID ) { $this->error(); return false; } else { $this->numRows = mysql_num_rows($this->queryID); return $this->getAll(); } }
When initializing the database link above, initConnect(false) calls Thinkphp/library/Think/Db/Db.class.php, pay attention to the false and true code implementation. true means calling the main library directly, false means calling the reading library with separate reading and writing.
/** * 初始化数据库连接 * @access protected * @param boolean $master 主服务器 * @return void */ protected function initConnect($master=true) { if(1 == C('DB_DEPLOY_TYPE')) // 采用分布式数据库 $this->_linkID = $this->multiConnect($master); else // 默认单数据库 if ( !$this->connected ) $this->_linkID = $this->connect(); } /** * 连接分布式服务器 * @access protected * @param boolean $master 主服务器 * @return void */ protected function multiConnect($master=false) { foreach ($this->config as $key=>$val){ $_config[$key] = explode(',',$val); } // 数据库读写是否分离 if(C('DB_RW_SEPARATE')){ // 主从式采用读写分离 if($master) // 主服务器写入 $r = floor(mt_rand(0,C('DB_MASTER_NUM')-1)); else{ if(is_numeric(C('DB_SLAVE_NO'))) {// 指定服务器读 $r = C('DB_SLAVE_NO'); }else{ // 读操作连接从服务器 $r = floor(mt_rand(C('DB_MASTER_NUM'),count($_config['hostname'])-1)); // 每次随机连接的数据库 } } }else{ // 读写操作不区分服务器 $r = floor(mt_rand(0,count($_config['hostname'])-1)); // 每次随机连接的数据库 } $db_config = array( 'username' => isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0], 'password' => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0], 'hostname' => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0], 'hostport' => isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0], 'database' => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0], 'dsn' => isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0], 'params' => isset($_config['params'][$r])?$_config['params'][$r]:$_config['params'][0], 'charset' => isset($_config['charset'][$r])?$_config['charset'][$r]:$_config['charset'][0], ); return $this->connect($db_config,$r); }
query method parameter is false, other delete, update, add read main library. This can be combined with the delete, save, and add operations in Thinkphp/library/Model.class.php, and the parameter is true.
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
PHPUsing stream_context_create() to simulate POST/GET requests_php tips
PHPHow to convert XML into an array_php tips
The above is the detailed content of Detailed explanation of read and write separation of MySQL database under thinkphp. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor
