日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php数据缓存

發布時間:2024/1/17 php 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 php数据缓存 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

用php進行微信開發時,碰到access_token長久保存的問題,以前都是用框架里的Cache直接set、get一下就完了。現在沒框架可用了,只好自己動手寫一個cache暫時用。

這個Cache類用來緩存一些具有時效性的數據,比如微信基礎接口的access_token、網頁Auth驗證的access_token等

下面的代碼使用本地文件進行數據的緩存

?

1 //測試 2 $cache = new Cache(); 3 $cache->dir = "../cc/"; 4 //$cache->setCache("zhang", "zhangsan", 100); 5 echo $cache->getCache("zhang"); 6 //$cache->removeCache("zhang"); 7 8 $cache->setCache("liu", "liuqi", 100); 9 echo $cache->getCache("liu"); 10 11 class Cache{ 12 public $cacheFile = "cache.json"; //文件 13 public $dir = "./cach2/"; //目錄 14 15 //緩存 16 public function setCache($name, $val, $expires_time){ 17 $file = $this->hasFile(); 18 //字符串轉數組 19 $str = file_get_contents($file); 20 $arr = json_decode($str, true); 21 22 //值為空,則移除該緩存 23 if(empty($val)){ 24 unset($arr[$name]); 25 }else{ 26 $arr[$name] = array("value"=>$val, "expires_time"=>$expires_time, "add_time"=>time()); 27 } 28 //數組轉字符串 29 $str = json_encode($arr); 30 file_put_contents($file, $str); 31 } 32 public function getCache($name){ 33 $file = $this->hasFile(); 34 35 //字符串轉數組 36 $str = file_get_contents($file); 37 $allArr = json_decode($str, true); 38 $arr = $allArr[$name]; 39 40 if(!$arr || time() > ($arr["expires_time"] + $arr["add_time"])){ 41 $this->removeCache($name); //過期移除 42 return false; 43 } 44 return $arr["value"]; 45 } 46 public function removeCache($name){ 47 $this->setCache($name, '', 0); 48 } 49 50 private function hasFile(){ 51 //如果不存在緩存文件,則創建一個 52 if(!file_exists($this->dir)){ 53 mkdir($this->dir); 54 } 55 if(!file_exists($this->dir . $this->cacheFile)){ 56 touch($this->dir . $this->cacheFile); 57 } 58 return $this->dir . $this->cacheFile; 59 } 60 }

上面的Cache類共有set、get、remove三種操作。另外還可以自定義緩存文件的保存路徑,只要設置Cache的dir屬性就可以了。

?

轉載于:https://www.cnblogs.com/lhat/p/5527033.html

總結

以上是生活随笔為你收集整理的php数据缓存的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。