以前寫過2篇文章,分別是:php
基於此,咱們再實現簡單的PHP+Mysql讀寫分離,從而提升數據庫的負載能力。算法
<?php class Db { private $res; function __construct($sql) { $querystr = strtolower(trim(substr($sql,0,6))); //若是是select,就鏈接slave服務器 if($querystr == 'select') { $res=$this->slave_select($sql); $this->res=$res; } //若是不是select,就鏈接master服務器 else { $res=$this->master_change($sql); $this->res=$res; } } /** * slave從庫返回sql查詢結果 * @param $sql * @return array */ private function slave_select($sql){ //該處只是隨機獲取slave節點的ip,固然,還能夠採用其餘算法獲取slave_ip $slave_server=$this->get_slave_ip(); $dsn="mysql:host=$slave_server;dbname=test"; $user='root'; $pass='123456'; $dbh=new PDO($dsn, $user, $pass); return $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC); } /**master主庫返回sql執行結果 * @param $sql * @return int */ private function master_change($sql){ $master_server='192.168.33.22'; $dsn="mysql:host=$master_server;dbname=test"; $user='root'; $pass='123456'; $dbh=new PDO($dsn, $user, $pass); return $dbh->exec($sql); } /** * 隨機獲取slave-ip * @return mixed */ private function get_slave_ip(){ $slave_ips=['192.168.33.33','192.168.33.44']; $count=count($slave_ips)-1; $random_key=mt_rand(0,$count); return $slave_ips[$random_key]; } /** * 獲取結果 * @return int */ public function get_res(){ return $this->res; } } $sql1 = "select * from t1"; $sql2 = "insert into t1 (name) values ('haha')"; $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());
更多精彩,請關注公衆號「聊聊代碼」,讓咱們一塊兒聊聊「左手代碼右手詩」的事兒。
sql