PHP+MYSQL讀寫分離
PHP+MYSQL讀寫分離
資料來源:
01.Mysql主從同步的實現原理 – https://www.jb51.net/article/108313.htm
02.詳解Mysql主從同步配置實戰 – https://www.jb51.net/article/108312.htm
03.PHP+MYSQL實現讀寫分離 – https://blog.csdn.net/AnPHPer/article/details/79812902
GITHUB: https://github.com/jash-git/PHP-MYSQL-read-and-write-separation
<?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());
2 thoughts on “PHP+MYSQL讀寫分離”
主從熱備+負載均衡/負載平衡(LVS + keepalived)
https://mp.weixin.qq.com/s?__biz=MzA3NTUzNjk1OA==&mid=2651562525&idx=1&sn=f8f38ed1875216ac7f57ba101b24e0ba&chksm=84900d4cb3e7845ae817f197091ec786e7ddc1cdb8d56459f02d530d3972802302321a382bfe&scene=0&xtrack=1&key=d7c04bb266a3c48ca7f70b3d18873634a8c728066729109f09edc94780ca39bec583200a465f4a55fab0fcb4a89ef40f72099bc10ead41a42f90f4dac6c14a233078f6f53aec3a592c5522dc2397d15f&ascene=1&uin=MjIwODk2NDgxNw%3D%3D&devicetype=Windows+10&version=62060833&lang=zh_TW&pass_ticket=sJh2JehbaR9lsCnDVP4CXdd228nDle3O0DrRn5mGdtS4ida5J7xetJiH0RIQ9KE9
碼雲(gitee):https://gitee.com/youzhibing
鏈接:https://www.cnblogs.com/youzhibing/p/5021224.html
PHP SQL MYSQL 負載均衡 / 負載平衡 / 備援 / 資料庫 / 備份