Laravel使用Caching快取資料減輕資料庫查詢壓力的方法_php執行個體

來源:互聯網
上載者:User
本文執行個體講述了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 '對不起,只有Administrator 群組才可進行此操作!';}

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

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

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

希望本文所述對大家基於Laravel架構的PHP程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.