phpcms缓存使用总结(memcached、eaccelerator、shm)
function query($sql , $type = '' , $expires = 3600, $dbname = '')
{
if($this->isclient)
{
$dbname = $dbname ? $dbname : $this->dbname;
$this->select_db($dbname);
}
/*
$this->iscache表示是否启动了数据库查询缓存
如果启用了数据库查询缓存且$type为CACHE且是select语句,则启用查询缓存
个人感觉这儿$type参数用strtoupper处理一下更好了
*/
if($this->iscache && $type == 'CACHE' && stristr($sql, 'SELECT'))
{
$this->caching = 1; //成员变量caching标识启用了数据库查询缓存,用在下面的fetch_array,num_rows,free_result函数中,其实用iscache就可以判断了,没有必要再用一个成员变量了
$this->expires = $expires; //数据库缓存数据的失效期
return $this->_query_cache($sql); //然后调用_query_cache方法
}
$this->caching = 0;
$func = $type == 'UNBUFFERED' ? 'mysql_unbuffered_query' : 'mysql_query';
if(!($query = $func($sql , $this->connid)) && $type != 'SILENT')
{
$this->halt('MySQL Query Error', $sql);
}
$this->querynum++;
return $query;
}
function _query_cache($sql)
{
$this->cache_id = md5($sql); //计算$sql的md5值,然后作为cache_id
$this->result = array();
$this->cursor = 0;
$this->cache_file = $this->_get_file(); //得到cache文件名
//如果cache数据已经过期,则重新从数据库中取得查询结果,然后保存在数据库中
if($this->_is_expire())
{
$this->result = $this->_get_array($sql); //从数据库中取结果
$this->_save_result(); //保存结果到缓存数据中
}
else
{
$this->result = $this->_get_result(); //缓存没过期直接取缓存数据
}
return $this->result;
}
function _get_file()
{
global $CONFIG;
//cache文件的主目录一般是data/dbcache
return $CONFIG['dbcachedir'].substr($this->cache_id, 0, 2).'/'.$this->cache_id.'.php';
}
function _is_expire()
{
global $PHP_TIME;
return !file_exists($this->cache_file) || ( $PHP_TIME > @filemtime($this->cache_file) + $this->expires );
}
/*
由于方法_get_array只是被方法_query_cache调用,所以在此方法里面直接用函数mysql_unbuffered_query了,因为mysql_unbuffered性能好一点,参考
http://bbs.chinaunix.net/viewthread.php?tid=958067&extra=page%3D4
*/
function _get_array($sql)
{
$this->cursor = 0;
$arr = array();
$result = mysql_unbuffered_query($sql, $this->connid);
while($row = mysql_fetch_assoc($result))
{
$arr[] = $row;
}
$this->free_result($result);
$this->querynum++;
return $arr;
}
function _save_result()
{
if(!is_array($this->result)) return FALSE;
dir_create(dirname($this->cache_file));
file_put_contents($this->cache_file, "
return ".var_export($this->result, TRUE).";
?>");
@chmod($this->cache_file, 0777);
}
function _get_result()
{
return include $this->cache_file;
}
function fetch_array($query, $result_type = MYSQL_ASSOC)
{
return $this->caching ? $this->_fetch_array($query) : mysql_fetch_array($query, $result_type);
}
//从数据库中获取查询的结果
function _fetch_array($result = array())
{
if($result) $this->result = $result;
return isset($this->result[$this->cursor]) ? $this->result[$this->cursor++] : FALSE;
}
function num_rows($query)
{
return $this->caching ? $this->_num_rows($query) : mysql_num_rows($query);
}
function free_result($query)
{
if($this->caching==1) $this->result = array();
else @mysql_free_result($query);
}
本站资源均来自互联网或会员发布,如果不小心侵犯了您的权益请与我们联系。我们将立即删除!谢谢!