有关数据库缓存的问题。Active Record Caching
本帖最后由 漫无目的 于 2009-2-22 13:11 编辑一。我看了手册,好像是分查询缓存和Active Record缓存,这两个是不是相同?我看写法都一样,只是多或少了个方法;
二。这个数据库缓存该怎么用呢?
类似:
$this->db->cache_on();
$this->db->select('id,title');
$this->db->get_where('user', array('user_id' => $_SESSION['currentUser']['user_id']));
$this->db->cache_off();
是否这样呢?谁可以给我一个说明呢谢谢!
如果想重新缓存该段数据,是否需要手动先用代码删除这段缓存,程序才会再次重新缓存? 貌似我发现,config/database.php中:
$db['localhost']['cache_on'] = TRUE;
如果是这样的话,无论是否在controller或是model中,查询语句之前$this->db->cache_on();
都会缓存起来的,所以要先把这个FALSE掉,再用$this->db->cache_off();灵活开关……
这个数据库缓存是多少时间缓存一次呢? CI默认的database 的 cache_on 一旦开启,永远不失效,除非自己删除。比较弱智。
我做了以下修改,可以设置过期时间:
CI database/DB_dirver.php 中 cache_on 函数替换为
function cache_on($expire_time=0) //add parm expire time - 缓存过期时间
{
$this->cache_expire_time = $expire_time;
$this->cache_on = TRUE;
return TRUE;
}
CI database/DB_cache.php 中 read 函数 替换为:
function read($sql)
{
if ( ! $this->check_path())
{
return $this->db->cache_off();
}
$segment_one = ($this->CI->uri->segment(1) == FALSE) ? 'default' : $this->CI->uri->segment(1);
$segment_two = ($this->CI->uri->segment(2) == FALSE) ? 'index' : $this->CI->uri->segment(2);
$filepath = $this->db->cachedir.$segment_one.'+'.$segment_two.'/'.md5($sql);
//判断是否过期 // cache_expire_time
if ( !file_exists($filepath) ) {
return false;
}
if ( $this->db->cache_expire_time > 0 && filemtime($filepath) < time() - $this->db->cache_expire_time) {
return false;
}
//判断是否过期结束
if (FALSE === ($cachedata = read_file($filepath)))
{
return FALSE;
}
return unserialize($cachedata);
}
在需要开启数据库缓存的地方写: $this→db→cache_on($SEC); $SEC 为需要缓存的秒数。 0 为永不过期。 如 $this→db→cache_on(3); 表示缓存3秒。3秒后自动失效。 很棒哦。谢谢!收藏啦,这贴要顶的... HEX呢,要给人家加分的啊
:)支持一把 我都想给他加分啊,没地方好加的说…… 呵呵,大家共同交流,共同进步 改得不错,同意加分 支持。。。。顶一个。 思路很清晰,一看就懂,很方便! 谢谢haohailuo
页:
[1]