日期:2012-06-01 浏览次数:20533 次
本代码是从uchome的代码修改的,是因为要解决uchome的效率而处理的。
PHP实现的Mysql读写分离
主要特性:
简单的读写分离
一个主数据库,可以添加更多的只读数据库
读写分离但不用担心某些特性不支持
缺点:同时连接两个数据库
英文比较烂,也写几个字吧
php code for mysql read/write split
feature:
simply rw split
one master,can add more slaves
support all mysql feature
link to the master and slave at the same time
PHP代码:
mysql_rw_php.class.php
<?php
/****************************************
*** mysql-rw-php version 0.1 @ 2009-4-16
*** code by hqlulu#gmail.com
*** http://www.aslibra.com
*** http://code.google.com/p/mysql-rw-php/
*** code modify from class_mysql.php (uchome)
****************************************/
class mysql_rw_php {
//查询个数
var $querynum = 0;
//当前操作的数据库连接
var $link = null;
//字符集
var $charset;
//当前数据库
var $cur_db = '';
//是否存在有效的只读数据库连接
var $ro_exist = false;
//只读数据库连接
var $link_ro = null;
//读写数据库连接
var $link_rw = null;
function mysql_rw_php(){
}
function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $halt = TRUE) {
if($pconnect) {
if(!$this->link = @mysql_pconnect($dbhost, $dbuser, $dbpw)) {
$halt && $this->halt('Can not connect to MySQL server');
}
} else {
if(!$this->link = @mysql_connect($dbhost, $dbuser, $dbpw)) {
$halt && $this->halt('Can not connect to MySQL server');
}
}
//只读连接失败
if(!$this->link && !$halt) return false;
//未初始化rw时,第一个连接作为rw
if($this->link_rw == null)
$this->link_rw = $this->link;
if($this->version() > '4.1') {
if($this->charset) {
@mysql_query("SET character_set_connection=$this->charset, character_set_results=$this->charset, character_set_client=binary", $this->link);
}
if($this->version() > '5.0.1') {
@mysql_query("SET sql_mode=''", $this->link);
}
}
if($dbname) {
$this->select_db($dbname);
}
}
//连接一个只读的mysql数据库
function connect_ro($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0){
if($this->link_rw == null)
$this->link_rw = $this->link;
$this->link = null;
//不产生halt错误
$this->connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, false);
if($this->link){
//连接成功
//echo "link ro sussess!<br>";
$this->ro_exist = true;
$this->link_ro = $this->link;
if($this->cur_db){
//如果已经选择过数据库则需要操作一次
@mysql_select_db($this->cur_