程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> Laravel使用Caching緩存數據減輕數據庫查詢壓力的方法

Laravel使用Caching緩存數據減輕數據庫查詢壓力的方法

編輯:PHP綜合

本文實例講述了Laravel使用Caching緩存數據減輕數據庫查詢壓力的方法。分享給大家供大家參考,具體如下:

昨天想把自己博客的首頁做一下緩存,達到類似於生成靜態頁緩存的效果,在群裡問了大家怎麼做緩存,都挺忙的沒多少回復,我就自己去看了看文檔,發現了Caching這個部分,其實之前也有印象,但是沒具體接觸過,顧名思義,就是緩存了,那肯定和我的需求有點聯系,我就認真看了看,發現的確是太強大了,經過很簡單的幾個步驟,我就改裝好了首頁,用firebug測試了一下,提高了幾十毫秒解析時間,當然了有人會笑這有必要嗎,豈不是閒的蛋疼?其實我想這是有必要的,只是在我這裡一來訪問人少(其實根本沒人還,嘿嘿....),二來我在首頁裡做的查詢目前還挺少,就一次,就是取得所有博文,如果一個頁面裡面有個七八次乃至十多次查詢,我想這個效果應該就很明顯了吧!(當然了,Raymond哥還有提到用更高級的專用緩存去做(memcached之類吧貌似),這是要自己能取得服務器控制權,能自由安裝軟件或者服務器本來就有這些緩存機制的情況下才能實現的,我需求比較簡單,也沒有這個環境去做,所以這裡就不考慮了)

閒話少說,開始吧,先說說我的具體需求:

一.  實現首頁的數據緩存,如果有沒過期的緩存,就不查數據庫,這樣基本模擬出靜態頁的效果(當然了,其實還是要經過php處理的)

二.  實現刷新指定緩存的功能(這裡只有首頁,就單指刷新首頁緩存了,這個功能,我做到了admin模塊下

具體實現:

一. 查閱文檔,找到能幫我實現需求的模塊

我查了一下文檔,發現了有Caching這樣一個模塊,顧名思義,就是緩存了,那它能否幫到我呢,看看先:

1. http://laravel.com/docs/cache/config  這裡是laravel的Caching模塊的實現

2. 文檔中有如下描述:

The Basics     Imagine your application displays the ten most popular songs as voted on by your users. Do you really need to look up these ten songs every time someone visits your site? What if you could store them for 10 minutes, or even an hour, allowing you to dramatically speed up your application? Laravel's caching makes it simple.

我簡單理解為:

假設你的應用展示了用戶投票最多的10首流行歌曲,你真的需要在每個人訪問你的網站的時候都去查一遍這10首歌嗎?如果你想按10分鐘或者是一小時的頻率來緩存查詢結果來加速你的應用,Laravel 的 caching緩存模塊能將使工作變得異常簡單.

嗯,從這段話,我已經了解到這完全符合我現在的需求了,接下來我只需要找到對應的使用方法和API,一步一步來就行了.

二.  學習相應API等

1. 還是上面文檔,裡面接著向下看,有如下描述:

By default, Laravel is configured to use the file system cache driver. It's ready to go out of the box with no configuration. The file system driver stores cached items as files in the cache directory. If you're satisfied with this driver, no other configuration is required. You're ready to start using it.

我簡單理解為:

默認情況下,Laravel使用文件系統作為緩存的驅動, 這是不需配置就可使用的, 文件系統驅動會將緩存的數據存入緩存目錄下的文件裡面去, 如果你覺得合適的話不需要做任何其他的配置直接開始用就行了.

當然了, 這也是符合我的想法的, 其實我就是想把頁面緩存成靜態頁文件, 用戶再次訪問時直接輸出緩存的靜態頁就ok了, 如果需要更高級的需求, 還可以使用其他的驅動,有數據庫驅動, memcached, redis驅動等, 很好很強大!

2. 接下來查看用例,找到使用方法

用例文檔在這: http://laravel.com/docs/cache/usage

可以看出, 裡面有 get, put, forever, remember, has, forget 等方法,這些方法使用也是基本上能 "望文生義" 就能搞定的,呵呵

具體使用方法文檔裡面已經說的夠詳細, 使用方法一目了然我就不細說了, 只在代碼裡面說吧

三. 具體實現

1. 我首頁之前的代碼

class Home_Controller extends Base_Controller {
 public function get_index() {
  $posts = Post::with('user')
     ->join('users', 'users.id', '=', 'posts.post_author')
      -> order_by('posts.created_at', 'desc')
       ->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'));
  $data = array();
  foreach($posts as $p){
   $data[] = array(
    'id'  => $p -> id,
    'support' => $p -> support,
    'against' => $p -> against,
    'username'=> $p -> username,
    'post_author' => $p -> post_author,
    'post_title' => $p -> post_title,
    'post_body' => $p -> post_body
   );
  }
  return View::make('home.index')
    -> with('posts', $data);
 }
}

這是我首頁的controller,作用只有一個, 就是從博文表裡面取得所有博文, 然後輸出, 每次有人訪問, 都要查表, 如果沒有發表新的博文, 也要查表, 的確有很多不必要的開銷

2.  下面是我改裝之後的代碼:

class Home_Controller extends Base_Controller {
 public function get_index() {
  // 添加靜態緩存支持
  // 如果不存在靜態頁緩存就立即緩存
  if ( !Cache::has('staticPageCache_home') ) {
   $data = array();
   $posts = Post::with('user')
      ->join('users', 'users.id', '=', 'posts.post_author')
       -> order_by('posts.created_at', 'desc')
        ->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'));
   foreach($posts as $p){
    $data[] = array(
     'id'  => $p -> id,
     'support' => $p -> support,
     'against' => $p -> against,
     'username'=> $p -> username,
     'post_author' => $p -> post_author,
     'post_title' => $p -> post_title,
     'post_body' => $p -> post_body
    );
   }
   $res = View::make('home.index')
    -> with('posts', $data);
   Cache::forever('staticPageCache_home', $res);
  }
  // 返回緩存的數據
  return Cache::get('staticPageCache_home');
 }
}

這裡我用到了三個api

1). Cache::has ,這個判斷是說如果當前不存在 staticPageCache_home 這個名字的緩存, 就立即去取數據

2). Cache::forever,  這個從用例文檔裡面可知是"永久緩存"的意思, 因為我一般都是很勤勞的,如果發表了博文,自己再去後台立即刷新一下緩存就好了, 所以不需要設置過期啊失效時間之類的, 當然這個是要按各自的具體需求來的

3). Cache::get , 這句是從緩存裡面取出 staticPageCache_home 這個名字的緩存, 然後作為響應內容返回

嗯, 就這麼簡單, 呵呵, 一個基本的緩存功能就完成了, laravel的確是不錯地!

3. 為後台添加刷新緩存功能

還是貼代碼吧, 不過也很簡單:

// 刷新首頁緩存(暫時只支持首頁)
public function get_refreshcache() {
 /*
  @var $GID admin組id
 */
 $GID = 1;
 if ( Auth::user() -> gid === 1 ) {
  $data = array();
  $posts = Post::with('user')
    ->join('users', 'users.id', '=', 'posts.post_author')
    -> order_by('posts.created_at', 'desc')
    ->get(array('posts.id', 'posts.support', 'posts.against', 'users.username', 'posts.post_author', 'posts.post_title', 'posts.post_body'));
  foreach($posts as $p){
   $data[] = array(
    'id'  => $p -> id,
    'support' => $p -> support,
    'against' => $p -> against,
    'username'=> $p -> username,
    'post_author' => $p -> post_author,
    'post_title' => $p -> post_title,
    'post_body' => $p -> post_body
   );
  }
  $res = View::make('home.index')
    -> with('posts', $data);
  Cache::forever('staticPageCache_home', $res);
  return '刷新首頁緩存成功!';
 }
 return '對不起,只有管理員組才可進行此操作!';
}

我給後台添加了一個項目, 對應這個方法, 方法內容和首頁的大同小異, 取數據, 然後Cache::forever 刷新一下緩存,就這麼簡單,當然了,上面的Auth::user() 判斷是個簡單的判斷,只有管理員組才能進行刷新操作,呵呵

嗯, 全部內容就這麼多, 很簡單, 歡迎童鞋們拍磚指正!

更多關於Laravel相關內容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優秀開發框架總結》、《smarty模板入門基礎教程》、《php日期與時間用法總結》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》

希望本文所述對大家基於Laravel框架的PHP程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved