博客首頁每次請求都要查詢數據庫獲取文章列表,訪問量上來後資料庫壓力劇增。Laravel 內建的 Cache 緩存系統提供了優雅的解決方案:將首頁渲染結果永久緩存,發布新文章時手動刷新,完美模擬靜態頁效果,大幅降低 DB 負載。
| 方法 | 用途 |
|---|---|
Cache::has($key) | 檢查緩存是否存在 |
Cache::get($key) | 讀取緩存值 |
Cache::forever($key, $value) | 永久存儲(無過期時間) |
Cache::forget($key) | 刪除指定緩存 |
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(['posts.id', 'posts.support', 'posts.against',
'users.username', 'posts.post_author',
'posts.post_title', 'posts.post_body']);
$data = [];
foreach ($posts as $p) {
$data[] = [
'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);
}
}
class Home_Controller extends Base_Controller {
public function get_index() {
// 緩存鍵名
$cacheKey = 'staticPageCache_home';
// 1. 嘗試讀取緩存
if (Cache::has($cacheKey)) {
return Cache::get($cacheKey);
}
// 2. 緩存不存在:查詢數據庫並構建視圖
$posts = Post::with('user')
->join('users', 'users.id', '=', 'posts.post_author')
->order_by('posts.created_at', 'desc')
->get(['posts.id', 'posts.support', 'posts.against',
'users.username', 'posts.post_author',
'posts.post_title', 'posts.post_body']);
$data = [];
foreach ($posts as $p) {
$data[] = [
'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
];
}
$response = View::make('home.index')->with('posts', $data);
// 3. 永久緩存響應對象
Cache::forever($cacheKey, $response);
return $response;
}
}
在 Admin 控制器新增 get_refreshcache() 方法:
public function get_refreshcache() {
// 權限校驗:僅管理員組(gid=1)可操作
if (Auth::user()->gid !== 1) {
return '對不起,只有管理員組才可進行此操作!';
}
// 重複上述查詢邏輯...
$posts = Post::with('user')->...->get([...]);
$data = [];
foreach ($posts as $p) { /* 組裝 $data */ }
$response = View::make('home.index')->with('posts', $data);
// 覆蓋舊緩存
Cache::forever('staticPageCache_home', $response);
return '刷新首頁緩存成功!';
}
使用 Firebug 測試:
隨著首頁查詢複雜度增加(關聯表、多條 SQL),優勢將更明顯。
redis 或 memcached 驅動,配置 config/cache.php 即可無縫遷移Cache::forget(),實現零手動維護Laravel Cache 以極簡的 API 實現了強大的緩存能力。對於中小型項目,file 驅動配合 forever() + 手動刷新已足夠應對大多數場景;隨著業務增長,平滑遷移到分佈式緩存只需修改配置,業務代碼零改動。這就是 Laravel 「優雅語法,強大功能」的典型體現。