0
点赞
收藏
分享

微信扫一扫

<内含丰富代码>京东秒杀列表网添加缓存机制

SPEIKE 2022-03-15 阅读 55

因为最近身体有点不舒服,很久没有更新了,请见谅。

还记得我们之前将京东秒杀列表那个软件用PHP移植到了网站(​​​​​​)上吗?但其实当时做得还不够完整。


每一次用户访问这个网站都会访问一次那个接口,当访问人数变得很多很多时,这个接口将会非常拥挤。此外,我们将网页缓存成html还有以下两个原因。



  1. 访问PHP网页的速度总是比html慢。PHP页面总是需要编译和执行

  2. 制作一个缓存页面可以避免京东方面怀疑这个接口的用途



其实缓存的运作原理很简单:


当缓存文件不存在或者过时时,重新访问页面,并保存成HTML文件到本地。

当缓存文件存在时,直接访问缓存文件。


下面是我的代码:


class Cache{
var $status = true;//开启缓存功能
var $cacheDir = "/home/www/XXX/cache/";//缓存文件的目录
var $cacheFile = "";//缓存文件的真实名字
var $timeOut = 1000;//内容被重复使用的最长时限
var $caching = true;//是否要对内容进行缓存 false则直接读取缓存文件内容

function startCache(){
ob_start();
if ($this->status){
$this->cacheFile = $this->cacheDir.urlencode($_SERVER['REQUEST_URI']);
//将访问此页面所需的URI编码并将其用于 URL 的请求部分
if (file_exists($this->cacheFile) && ((fileatime($this->cacheFile) + $this->timeOut)> time()) ){
//从缓存文件中读取内容
$handle = fopen($this->cacheFile,'r');
$html = fread($handle,filesize($this->cacheFile));
fclose($handle);
echo $html;
$this->caching = false;
exit();
}else{
$this->caching = true;
}
}
}

//如果实际页面尚未被缓存,并且caching标志被设置成True;那么此函数将首先将页面中的所有输出保存成缓存文件,然后显示页面。
function endCache(){
if ($this->status){
if ($this->caching){
$html = ob_get_clean();
echo $html;
$handle = fopen($this->cacheFile,"w")or die("Unable to open file!");
fwrite($handle,$html);
fclose($handle);
}
}
}
}



在要做缓存的PHP页面开头的部分声明对象并使用即可。


<?php
require_once('cache.php');
//创建一个缓存类对象CacheManager
$CacheManager = new Cache();
//调用startCache方法,读取缓存
$CacheManager->startCache();


在尾部则是


$CacheManager->endCache();


除此之外,当缓存文件过多的时候,我们需要清理掉。


  function cleanCache(){
       
if ($handle = opendir($this->cacheDir)){
           
while(false !== ($file = readdir($handle))){
               
if (is_file($this->cacheDir.$file)) unlink($this->cacheDir.$file);
           }
           
closedir($handle);
       }
   }


重新建立一个PHP文件调用cleanCache:


<?php
require_once('cache.php');
$CacheManager = new Cache();
$CacheManager->cleanCache();
?>


再使用Crontab定时脚本定时访问这个PHP文件清理这些缓存即可:



终端中输入 crontab-e

进入crontab编辑页面

添加 0 0 * * * /usr/bin/php /home/www/xxx/clear.php 





欢迎关注微信公众号:幻象客

​​

​​

​​

​​

举报

相关推荐

0 条评论