Zend Framework中如何实现MySQL的读写分离

<?php

/**
* Model
*
* @author li
* @version
*/

require_once 'Zend/Db/Table/Abstract.php';

abstract class Model extends Zend_Db_Table_Abstract {
private $_master;
private $_slave;
private $_dbconf;
protected function _setup(){
if (!$this->_slave instanceof Zend_Db_Adapter_Abstract){
$this->setDblink(0);
}
$frontendOptions = array(
'lifeTime' => 86400, // 两小时的缓存生命期
'automatic_serialization' => true
);
$backendOptions = array(
'cache_dir' => _CACHEPATH_.'/models',
);
$cache = Zend_Cache::factory('Core','File', $frontendOptions, $backendOptions);
$this->_metadataCache=$cache;
parent::_setup();
}
public function db_getprofiler(){
$db=$this->getDefaultAdapter();
$profiler = $db->getProfiler();
$profiler->setFilterQueryType(Zend_Db_Profiler::SELECT |
Zend_Db_Profiler::QUERY
);
$result = $profiler->getQueryProfiles();
$totalTime = $profiler->getTotalElapsedSecs();
$queryCount = $profiler->getTotalNumQueries();
$longestTime = 0;
$longestQuery = null;
foreach ($result as $query) {
if ($query->getElapsedSecs() > $longestTime) {
$longestTime = $query->getElapsedSecs();
$longestQuery = $query->getQuery();
}
}
echo '共执行 ' . $queryCount . ' 次查询 在 ' . $totalTime .
' 秒' . "<br/>";
echo '平均查询时间: ' . $totalTime / $queryCount .
' 秒<br/>';
echo '每秒执行查询数: ' . $queryCount / $totalTime . "<br/>";
echo '最长查询时间: ' . $longestTime . "<br/>";
echo "最长查询语句: \n" . $longestQuery . "<br/>";
}
public function insert($data){
if (!$this->_master instanceof Zend_Db_Adapter_Abstract){
$this->setDblink(1);
}
$this->_master->insert($this->_name,$data);
}
public function update($data,$where){
if (!$this->_master instanceof Zend_Db_Adapter_Abstract){
$this->setDblink(true);
}
$this->_master->update($this->_name,$data,$where);
}
/**
* 连接数据库
* @param int $ismaster 1 连主库 0 连辅库
*/
private function setDblink($ismaster){
switch(_DOMAINPRI_){
default:
$strInclude = _CONFPATH_.'/db/db.config.php';
}
if(!is_array($this->_dbconf)){
$this->_dbconf = include_once($strInclude);
}
if($ismaster){
$param = $this->_dbconf['master'];
$this->_master = Zend_Db::factory($param['adapter'],$param['params']);
}else{
$rand = array_rand($this->_dbconf['slave']);
$param=$this->_dbconf['slave'][$rand];
$this->_slave = Zend_Db::factory($param['adapter'],$param['params']);
$this->setDefaultAdapter($this->_slave);
}
}
/**
* 设置主库为当默认Adapter
*/
public function setMasterasDefault(){
if (!$this->_master instanceof Zend_Db_Adapter_Abstract){
$this->setDblink(1);
}
$this->setDefaultAdapter($this->_master);
}
/**
* 设置辅库为当默认Adapter
*/
public function setSlaveDefault(){
if (!$this->_master instanceof Zend_Db_Adapter_Abstract){
$this->setDblink(0);
}
$this->setDefaultAdapter($this->_slave);
}
}
?>

posted @ 2012-07-24 15:26  信管小子  阅读(680)  评论(0编辑  收藏  举报