PHP访问数缓存处理

时间:2021-06-01 14:44:05

利用Redis或Memcache作为MySQL的缓存,采用是ThinkPHP框架。

方法一

  • 采用ThinkPHP的S方法:
$savedata['uid']=session('uid');
$savedata['ip']=$_SERVER['REMOTE_ADDR'];
$savedata['url']=$_SERVER['REQUEST_URI'];
$savedata['created_time']=time();
$savedata['created_by']=session('uid'); $cache = S(array('type'=>'redis','host'=>'127.0.0.1','port'=>'6379','prefix'=>'think','expire'=>600000));
// 获取缓存
$visitor_data = $cache->visitor_data;
if(empty($visitor_data)){
$visitor_data=array();
}
array_push($visitor_data, $savedata); // 设置缓存
$cache->visitor_data = $visitor_data; if(count($visitor_data)>3){
foreach ($visitor_data as $key => $value) {
 $m = M("VisitorLog");
$m->add($value);
}
// 删除缓存
unset($cache->visitor_data);
}

方法二

  • 采用Redis
$savedata['uid']=session('uid');
$savedata['ip']=$_SERVER['REMOTE_ADDR'];
$savedata['url']=$_SERVER['REQUEST_URI'];
$savedata['created_time']=time();
$savedata['created_by']=session('uid'); // 连接本地的 Redis 服务
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379); //查看服务是否运行
if(empty($redis)){
return dataResult(null,'',0);
}
//存储数据到列表中
$redis->lpush("visitor_data",json_encode($savedata));
// 获取存储的数据并输出
$len=$redis->llen("visitor_data");
if($len>2){
$visitor_data = $redis->lrange("visitor_data",0,$len);
foreach ($visitor_data as $key => $value) {
$m = M("VisitorLog");
$m->add(json_decode($value,true));
}
$redis->del("visitor_data");
}

方法三

  • 采用Memcache:
$savedata['uid']=session('uid');
$savedata['ip']=$_SERVER['REMOTE_ADDR'];
$savedata['url']=$_SERVER['REQUEST_URI'];
$savedata['created_time']=time();
$savedata['created_by']=session('uid'); $memcache = new \Memcache; //创建一个memcache对象
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect"); //连接Memcached服务器
$visitor_data = $memcache->get('visitor_data'); //从内存中取出key的值
if(empty($visitor_data)){
$visitor_data=array();
}
if(count($visitor_data)>2){
foreach ($visitor_data as $key => $value) {
$m = M("VisitorLog");
$m->add($value);
}
unset($visitor_data);
$visitor_data=array();
}
array_push($visitor_data,$savedata);
$memcache->set('visitor_data', $visitor_data); //设置一个变量到内存中,名称是key 值是test