首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Laravel Cache 緩存實戰:為首頁數據查詢減壓,實現類靜態頁加速效果

     編輯:PHP 綜合知識

博客首頁每次請求都要查詢數據庫獲取文章列表,訪問量上來後資料庫壓力劇增。Laravel 內建的 Cache 緩存系統提供了優雅的解決方案:將首頁渲染結果永久緩存,發布新文章時手動刷新,完美模擬靜態頁效果,大幅降低 DB 負載。

需求分析

  • 首頁數據緩存:若緩存存在且未過期,直接返回,跳過數據庫查詢
  • 後台手動刷新:發文後點擊按鈕即時更新首頁緩存
  • 輕量級部署:使用預設 file 驅動,無需額外安裝 Redis/Memcached

核心 API 速覽

方法用途
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 測試:

  • 未緩存:首頁解析耗時 ~120ms
  • 緩存命中:首頁解析耗時 ~40ms
  • 提升 60%+ 響應速度

隨著首頁查詢複雜度增加(關聯表、多條 SQL),優勢將更明顯。

進階優化方向

  • 驅動升級:生產環境建議切換到 redis 或 memcached 驅動,配置 config/cache.php 即可無縫遷移
  • 緩存標籤:Laravel 5.5+ 支持標籤化管理,可批量清理相關頁面緩存
  • 自動失效:結合模型觀察器,文章發布/更新/刪除時自動 Cache::forget(),實現零手動維護

總結

Laravel Cache 以極簡的 API 實現了強大的緩存能力。對於中小型項目,file 驅動配合 forever() + 手動刷新已足夠應對大多數場景;隨著業務增長,平滑遷移到分佈式緩存只需修改配置,業務代碼零改動。這就是 Laravel 「優雅語法,強大功能」的典型體現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved