1、Introduction
之前写过2篇文章,分别是:
基于此,我们再实现简单的PHP+Mysql读写分离,从而提高数据库的负载能力。
2、代码实战
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
<?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());
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://segmentfault.com/a/1190000008664288