美文网首页
Mysql 读写分离 Demo -- PHP版

Mysql 读写分离 Demo -- PHP版

作者: NemoWei | 来源:发表于2016-10-20 18:51 被阅读0次

备注:
Mysql 主库 :192.168.157.88
Mysql 从库 :192.168.157.89

<?PHP  
/** 
* mysql读写分离 
*/  
class db   
{   
    //定义链接
    public $host = array(
                'read' =>array(
                        'host'=>'192.168.157.89:3306',
                        'username' => 'root',
                        'password' => 'root'
                ),
                'write' =>array(
                        'host'=>'192.168.157.89:3306',
                        'username' => 'root',
                        'password' => 'root'
                )
        );
    public function __construct($sql)   
    {   
        $chestr = strtolower(trim($sql));  
        
        //根据 sql 判断链接库  
        if(substr($chestr,0,6)=='select')   
        {   
       
            echo 'I am using select db..<br>';  
            $rand = rand(0,1);
            $middleArr = array('read','write');//读库分流
            
            $link = mysql_connect($this->host[$middleArr[$rand]]['host'], $this->host[$middleArr[$rand]]['username'], $this->host[$middleArr[$rand]]['password']) or die("Could not connect: " . mysql_error());   
            mysql_select_db("nemo");   
            $result = mysql_query($sql);   
            while ($row = mysql_fetch_array($result, MYSQL_NUM))   
            {   
                printf("%s %s", $row[0],$row[1]);
                echo "<br/>";
            }   
            echo mysql_get_host_info($link).mysql_get_server_info($link).mysql_get_proto_info($link).mysql_get_client_info().'<br>';      
        }   
        else  
        {   
            echo 'I am using insert db..<br>';  
            
            $link = mysql_connect($this->host['write']['host'], $this->host['write']['username'], $this->host['write']['password']) or die("Could not connect: " . mysql_error());   
            mysql_select_db("nemo");   
            $result = mysql_query($sql);   
            //echo $sql;
            //echo @mysql_affected_rows($result);   
            //echo mysql_get_host_info($link).mysql_get_server_info($link).mysql_get_proto_info($link).mysql_get_client_info().'<br>';       
        }   
            
    }   
}   
$arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
foreach($arr as $k=>$v){
    //echo $v;
    $d = new db(" INSERT INTO test values('nemo{$v}','nemowei{$v}') ");  
}
 

$d2 = new db("SELECT * from `test`");  

测试结果

Paste_Image.png Paste_Image.png Paste_Image.png

相关文章

网友评论

      本文标题:Mysql 读写分离 Demo -- PHP版

      本文链接:https://www.haomeiwen.com/subject/qzzfuttx.html