PHP + MYSQL implements simple read/write splitting practices, and phpmysql read/write practices
1. Introduction
I have written two articles:
Principle of Mysql master-slave Synchronization
MySQL master-slave synchronization practice
Based on this, we can implement simple PHP + Mysql read/write separation to improve the load capacity of the database.
2. Code practice
<? Phpclass Db {private $ res; function _ construct ($ SQL) {$ querystr = strtolower (trim (substr ($ SQL,); // If select is used, connect to the slave server if ($ querystr = 'select') {$ res = $ this-> slave_select ($ SQL); $ this-> res = $ res ;} // if it is not a select statement, connect to the master server else {$ res = $ this-> master_change ($ SQL); $ this-> res = $ res ;}} /*** slave returns the SQL query result from the database * @ param $ SQL * @ return array */private function slave_select ($ SQL) {// only the ip address of the slave node is randomly obtained. Of course, you can also use other algorithms to obtain slave_ip $ slave_server = $ this-> get_slave_ip (); $ dsn = "mysql: host = $ slave_server; dbname = test "; $ user = 'root'; $ pass = '000000'; $ dbh = new PDO ($ dsn, $ user, $ pass ); return $ dbh-> query ($ SQL)-> fetchAll (PDO: FETCH_ASSOC );} /** the master database returns the SQL Execution result * @ param $ SQL * @ return int */private function master_change ($ SQL) {$ master_server = '2017. 168.33.22 '; $ dsn = "mysql: host = $ master_server; dbname = test"; $ user = 'root'; $ pass = '2016 '; $ dbh = new PDO ($ dsn, $ user, $ pass); return $ dbh-> exec ($ SQL );} /*** randomly obtain the slave-ip * @ return mixed */private function get_slave_ip () {$ slave_ips = ['2017. 168.33.33 ', '2017. 168.33.44 ']; $ count = count ($ slave_ips)-1; $ random_key = mt_rand (0, $ count); return $ slave_ips [$ random_key];} /*** get result ** @ return int */public function get_res () {return $ this-> res; }}$ sql1 = "select * from t1 "; $ sql2 = "insert into t1 (name) values ('hahahaha')"; $ sql3 = "delete from t1 where id = 1 "; $ sql4 = "update t1 set name = 'Jerry 'where id = 2"; $ db = new Db ($ sql1); // $ db = new Db ($ sql2 ); // $ db = new Db ($ sql3); // $ db = new Db ($ sql4); var_dump ($ db-> get_res ());
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.