本文讲述的是PHP访问数据缓存处理,利用Redis或Memcache作为MySQL的缓存,采用是ThinkPHP框架。
$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); }
$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"); }
$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
想了解更多PHP相关知识,一定要去看PHP中文网的PHP视频教程哦!
以上是PHP访问数据缓存处理的详细内容。更多信息请关注PHP中文网其他相关文章!