Home>Article>Backend Development> PHP access data cache processing

PHP access data cache processing

little bottle
little bottle forward
2019-04-16 17:54:43 3270browse

This article talks about PHP access data caching processing, using Redis or Memcache as the cache of MySQL, and using the ThinkPHP framework.

Method 1

  • Use ThinkPHP’s S method:
$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); }

Method 2

  • Use 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"); }

Method 3

  • Use 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

If you want to know more about PHP, be sure to visit the PHP Chinese websitePHP video tutorialOh!

The above is the detailed content of PHP access data cache processing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete