1.文件缓存
一般情况下我们都将数据先缓存在文件当中,当需要的时候直接从文件中读取。则可以减少数据库查询的压力。
class File{
private$_dir;
constEXT = '.txt';
publicfunction __construct(){
$dir= str_replace('\\', '/', dirname(__FILE__));
$this->_dir= $dir.'/files/';
}
/**
* $value==null时删除缓存
*
*/
publicfunction cacheData($key,$value='',$cacheTime=0){
$filename= $this->_dir.$key.self::EXT;
//echo$filename;exit;
$dir= dirname($filename);
if(is_null($value)){//删除缓存
return unlink($filename);
}
if($value!= ''){//添加缓存
if(!is_dir($dir)){
mkdir($dir,0777);
}
if(file_put_contents($filename,json_encode($value),FILE_APPEND ) !== false){
echo 'succeed';
}
}else{
//查询缓存
if(!is_file($filename)){
return false;
}else{
return json_decode(file_get_contents($filename),true);
}
}
}
}
//测试案例
$file = new File();
$result = array(
'code'=> '555',
'message'=> 'message'
);
if($res =$file->cacheData('first',null)){
print_r($res);exit;
echo 'succeed';
}else{
echo 'fail';
}
redis的安装和使用
1.安装redis
Yum -y install redis
2. 安装php-redis扩展
yum install php-redis
3. 启动redis,并设定开机自动启动
service redis start
chkconfig redis on
4.开启终端
Redis-cli
<?php
$redis= new Redis();
$redis->connect('127.0.0.1',6379);
$redis->set('leyan',123);
echo $redis->get('leyan');
$redis->setex('leyan',12,'haha');//设置12秒内的存储