Ecshop Source Code Study Query Cache
query_cache数据库类中的查询缓存
ecshop有三种缓存解析
ecshop有三种缓存,query_cache(数据库查询缓存)、static_cache(静态缓存)和cache(普通的缓存)
今天主要来看的是
第一种数据库查询缓存。
数据库查询缓存文件在ecshop/upload/temp/query_cache目录下面
在ecshop/upoad/下面编写一个测试文件test1.php,用来测试它的查询缓存。
代码如下:
//前面三句主要是做些初始化工作,让我可以使用ecshop里面的类库函数等 define(‘IN_ECS’, true); define(‘ECS_ADMIN’, true); require(dirname(__FILE__) . ‘/includes/init.php’); /******* 这里的GetALLCached函数里面带了一个sql语句的参数, 这里可以先简单的把这个函数理解成执行sql查询获取结果的操作。 *******/ $article_array = $db->GetALLCached(“SELECT article_id, title FROM ” . $ecs->table(“article”) . ” WHERE cat_id != 0 AND is_open = 1 AND open_type = 0 ORDER BY article_id DESC LIMIT 0,4″); print_r($article_array); //打印出来的数组结果如下 /* Array ( [0] => Array ( [article_id] => 35 [title] => “沃”的世界我做主 ) [1] => Array ( [article_id] => 34 [title] => 3G知识普及 ) [2] => Array ( [article_id] => 32 [title] => 手机游戏下载 ) [3] => Array ( [article_id] => 31 [title] => 诺基亚6681手机广告欣赏 ) */
我们现在去看ecshop/upload/temp/query_caches目录,发现多了一个sqlcache的文件,我们打开来看
exit;1273944294a:4:{i:0;a:2:{s:10:”article_id”;s:2:”35″;s:5:”title”;s:27:”“沃”的世界我做主”;} i:1;a:2:{s:10:”article_id”;s:2:”34″;s:5:”title”;s:14:”3G知识普及”;} i:2;a:2:{s:10:”article_id”;s:2:”32″;s:5:”title”;s:18:”手机游戏下载”;} i:3;a:2:{s:10:”article_id”;s:2:”31″;s:5:”title”;s:31:”诺基亚6681手机广告欣赏”;}}
发现是一串经过什么处理的东西(实际上是经过serialize函数处理)
这个sqlcache里面的东西实际上就是刚才打印出来的print_r($article_array)的结果。
在刚才的test1.php文件中使用了$db->GetALLCached()这个函数
它来自ecshop/upload/includes/cls_mysql.php文件中
GetALLCached()该函数会调用到2个实际来处理缓存(就是刚才的sqlcache文件)的函数。
第一个函数是setSqlCacheData
/* 设置查询缓存的函数,如果GetALLCached函数参数中的sql语句的查询结果没有被缓存, 则先执行的是这个函数,该函数的作用是将sql获取的结果数组经过序列化以后存储在某个路径下面 */ function setSqlCacheData($result, $data) { if ($result['storecache'] === true && $result['filename']) { @file_put_contents($result['filename'], ‘ exit;’ . time() . serialize($data)); clearstatcache(); } }
第二个函数是getSqlCacheData
/*******
该函数的主要作用是从sqlcache数据库查询缓存文件中将被序列化过的文件还原。
这样就如果再执行某条sql语句,该sql语句的结果已经被缓存下来,就不用再去数据库查询了,直接去缓存文件中读取。
******/
function getSqlCacheData($sql, $cached = ”)
{
$sql = trim($sql);
$result = array();
$result['filename'] = $this->root_path . $this->cache_data_dir . ‘sqlcache_’ . abs(crc32($this->dbhash . $sql)) . ‘_’ . md5($this->dbhash . $sql) . ‘.php’;
$data = @file_get_contents($result['filename']);
if (isset($data{23}))
{
$filetime = substr($data, 13, 10);
$data = substr($data, 23);
if (($cached == ‘FILEFIRST’ && time() > $filetime + $this->max_cache_time)
|| ($cached == ‘MYSQLFIRST’ && $this->table_lastupdate($this->get_table_name($sql)) > $filetime))
{
$result['storecache'] = true;
}
else
{
$result['data'] = @unserialize($data);
if ($result['data'] === false)
{
$result['storecache'] = true;
}
else
{
$result['storecache'] = false;
}
}
}
else
{
$result['storecache'] = true;
}
return $result;
}