物流中公路运输的现状:php 数据缓存 ? Connie的博客

来源:百度文库 编辑:中财网 时间:2024/04/28 01:08:26

php 数据缓存

2010 年 11 月 25 日 http://blog.yiiren.com

php程序常规的获取数据的流程是:

1.用户向php程序发送请求

2.php请求从数据库中取出数据

3.发送给用户

但是当网站的访问量非常大的时候数据库往往成为制约系统性能的瓶颈,为了减轻大规模请求对数据库造成的压力,简单的方法可以采用数据缓存来减轻数据库的压力,下面就简单的介绍一下常规的数据缓存方法:

具体的步骤:

1.用户请求

2.判断缓存是否存在或者是否过期

3.如果缓存不存在 或者缓存已经过期,从数据库中读出数据;如果没有过期,读取缓存

4.发送给用户

文件方式缓存数据示例代码:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 //数据库连接省略   $cache_dir = 'cache'; //缓存文件夹 $cache_time = '60'; //缓存时间 $sql = 'select * from test'; $cache_file = $cache_dir.'/'.md5($sql); //以sql语句的md5值作为缓存文件名(当然也可以用其他方式)   //如果缓存存在并且缓存未过期 if(file_exists($cache_file)  && time() - filemtime($cache_file) < $cache_time){     $data = unserialize(file_get_contents($cache_file)); //读取缓存后反序列化 }else{     //读取数据库     $query = mysql_query($sql);     //省略...     $data = "数据库中读取...";     //把读取的数据序列化后写入缓存     file_put_contents($cache_file,serialize($data)); } //呵呵,这里就是想要的数据 print_r($data);

Memcache缓存数据示例:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 //先要安装memcache服务端 和memcache php扩展 $memcache = new Memcache; $memcache->connect('localhost', 11211) or die ("Could not connect"); $cache_time = '60'; //缓存时间 $sql = 'select * from test'; $key = md5($sql);   if(!$memcache->get($key)){//如果缓存不存在     //读取数据库     $query = mysql_query($sql);     //省略...     $data = "数据库中读取...";     //把读取的数据写入缓存     $memcache->set($key, $data, 0, $cache_time); }else{//缓存存在     $data = $memcache->get($key); //读取缓存 } print_r($data);