+ -
当前位置:首页 → 问答吧 → 加速你的应用程序(缓存类)

加速你的应用程序(缓存类)

时间:2008-10-09

来源:互联网

对数据库频繁的操作是很费时间的,所以要适当地使用缓存类来加速自己的程序。

[php]
<?php
/**
* cache class
*/

class Cache {
    /**
     * 缓存保存的路径
     *
     * @var string
     */
    var $cache_path;
   
    /**
     * 过期时间
     *
     * @var integer
     */
    var $time = 60;
   
    /**
     *
     * 缓存文件的扩展名
     *
     * @var String
     */
    var $ext = 'cc';
   
    /**
     * 构造函数
     *
     * @param string $cache_path  缓存保存的路径,默认为cache文件夹
     * @return Cache
     */
    function Cache($cache_path = 'cache') {
        if(is_dir($cache_path)) {//如果存在这个文件夹
            $this->cache_path = rtrim($cache_path,'/').'/';
        } else {
            die('cache dir is not exists.');
        }
    }
   
    /**
     * 设置过期时间
     *
     * @param integer $time  过期时间
     * @return boolean
     */
    function setTime($time) {
        if(isset($time) && is_integer($time)) {//检查$time是否为整数
            $this->time = $time;
            return true;
        } else {
            return false;
        }
    }
   
   
  /**
   * 设置缓存的扩展名
   *
   * @return Boolean
   */
    function setExt($ext) {
        if(preg_match('/[a-zA-Z0-9.]{1,}/',$ext)) {
            //扩展名只能由字母,数字和.组成
            $this->ext = $ext;
            return true;
        } else {
            return false;
        }
    }
   
    /**
     * 读取缓存
     *
     * @param string $cache_id   要读取缓存的ID
     * @return mixed
     */
    function read($cache_id) {
        $cache_file = $this->cache_path.$cache_id.'.'.$this->ext;//取得缓存的路径
        if(!file_exists($cache_file)) {//如果缓存不存在,返回false
            return false;
        }
        $mtime = filemtime($cache_file);//取得缓存的生成时间
        if((time() - $mtime) > $this->time) {//判断缓存是否过期
            return false;
        } else {//读取缓存
            $fp = fopen($cache_file,'r');//打开缓存文件
            $content = fread($fp,filesize($cache_file));//读取缓存内容
            fclose($fp);
            unset($fp);
            if($content) {
                return unserialize($content);//返回反序列化的缓存内容
            } else {
                return false;
            }
        }
    }
   
    /**
     * 写入缓存
     *
     * @param string $content   缓存内容
     * @param string $cache_id  缓存ID
     * @return boolean
     */
    function write($content,$cache_id) {
        $cache_file = $this->cache_path.$cache_id.'.'.$this->ext;//获得缓存文件名
        if(file_exists($cache_file)) {//如果存在相同ID的缓存,就把它删除
            @unlink($cache_file);
        }
        $fp = fopen($cache_file,'w');//创建缓存文件
        $yon = fwrite($fp,serialize($content));//写入序列化后的缓存内容
        fclose($fp);
        unset($fp);
        $yon?return true:return false;
    }
   
    /**
     * 清除所有的缓存
     *
     * @param string $path
     * @return boolean
     */
    function cleanCache($path = 'cache') {
        if(!is_dir($path)) {
            $path = $this->cache_path;
        }
        $path = rtrim($path,'/').'/';
        $handler = opendir($path);//打开缓存目录
        while (($f = readdir($handler)) !== false) {//循环缓存目录
            if(!is_dir($f)) {
                if($f != '.' && $f != '..') {
                    @unlink($path.$f);
                }
            } else {
                $this->cleanCache($f);//递归删除所有的缓存文件
            }
        }
        return true;
    }
}

?>
[/php]

使用方法:

<?php
requrie_once('cache.class.php');
requrie_once('db.class.php');

$cache = new Cache('/cache/');
if(!($result = $cache->read('content'))) {
    $db = new DB();
    $db->query('select * form my_table where id=1');
    $result = $db->fetch();
    $cache->write($result, 'content');
}

print_r($result);
?>


作者: liexusong   发布时间: 2008-10-09


        if(fwrite($fp,serialize($content))) {//写入序列化后的缓存内容
            fclose($fp);
            unset($fp);
            return true;
        } else {
            fclose($fp);
            unset($fp);
            return false;
        }



这一句有些重复的说,可以这样写

$result = fwrite($fp,serialize($content))
fclose($fp);
unset($fp);
return $result ? true : false;

作者: 飞翔de希望   发布时间: 2008-10-13

[code]/**
* 写入缓存
*
* @param string $content 缓存内容
* @param string $cache_id 缓存ID
* @return boolean
*/
function write($content,$cache_id) {
$cache_file = $this->cache_path.$cache_id.'.'.$this->ext;//获得缓存文件名
if(file_exists($cache_file)) {//如果存在过期的缓存,就把它删除
@unlink($cache_file);
}
$fp = fopen($cache_file,'w');//创建缓存文件
if(fwrite($fp,serialize($content))) {//写入序列化后的缓存内容
fclose($fp);
unset($fp);
return true;
} else {
fclose($fp);
unset($fp);
return false;
}
}[/code]这里的
if(file_exists($cache_file)) {//如果存在过期的缓存,就把它删除
@unlink($cache_file);
}
有判断是否过期吗?

作者: ylcz   发布时间: 2008-10-13

谢谢两位大哥的指导!!错误已经改过了!

作者: liexusong   发布时间: 2008-10-13

楼主加油哦。

作者: luzhou   发布时间: 2008-10-13

谢谢浅玉大哥支持!!!我会努力的!

作者: liexusong   发布时间: 2008-10-13

希望楼主给个例子,我没搞过缓存

作者: ylcz   发布时间: 2008-10-15

lz代码格式和注释。很祥细。格式也很规范。是我最需要改进的。

可lz有没有想过。在高并发的情况下。是否能保证正确运行!

作者: superpower   发布时间: 2008-11-25

原帖由 ylcz 于 2008-10-15 11:05 发表
希望楼主给个例子,我没搞过缓存
就是啊,怎么用啊?

作者: 1987   发布时间: 2008-12-08

学到缓存的原理等不少东西就不错了,
高并发再说

作者: wodoe   发布时间: 2009-01-13

雷人的本义是云层放电时击倒某人。其网络语言意义源自2008年08月26日的一则新闻“男子发誓欠钱被雷劈,话音刚落被雷电击伤”,福清东瀚一男子为赖账,手持铁棍时不惜对天发誓,称如确实欠钱就遭天打雷劈,结果一分钟后就遭雷击,所幸最终经抢救脱离生命危险。 从此以后,“被雷到了”成为让人感到很无语,很无奈,很“冷”的代名词。































--------------------------------------------------------------------------------------------------------------------------------------
海泡石电缆管  维纶电缆管  电缆保护管   风水预测  网站推广软件 上海湖南特产  供求信息群发软件

作者: fgca08   发布时间: 2009-09-09

怎么全是AD?

作者: 邂逅米莱   发布时间: 2009-09-16

谢谢 lz的分享

作者: ainiaa   发布时间: 2009-09-16

不错的缓存  。。

作者: oik550   发布时间: 2009-09-24

做3个俯卧撑,,,走人。。。楼下继续。。。
















斗破苍穹 http://www.shucheng.com/book/5/5575/

作者: 智没平   发布时间: 2009-09-29