PHP通過檔案儲存體來實現緩衝,
PHP通過檔案儲存體來實現緩衝在一些資料庫資料記錄較大,但是伺服器有限的時候,可能一條MySQL查詢就會好幾百毫秒,一個簡單的頁面一般也有十幾條查詢,這個時候也個頁面載入下來基本要好幾秒了,如果並發量高的話伺服器基本就癱瘓了,造成一個頁面很久也載入不下來,這個時候我們可以使用檔案快取來緩解下MySQL的壓力,下面給個使用例子。
[php] view plaincopy
- <?php
-
- //頁面商務邏輯處理,獲得結果
- $objPage = new Page_IndexModel($arrParams);
-
- //一系列的商務邏輯放在了objPage中,調用process方法獲得結果集
- $arrResult = $objPage->process();
-
- //獲得結果後smarty賦值
- $smarty->assign($arrResult);
-
- //輸出模板
- $smarty->display();
-
- ?>
現在我們用檔案快取來略過Page業務處理這一步
[php] view plaincopy
- <?php
-
- $cachFile = './index.php';
- //快取檔案存在且時間不超過一小時,則直接使用緩衝的結果集,不在進行任何的MySQL查詢了
- if(file_exists($cacheFile) && time()-filemtime($cachFile) < 3600) {
- //使用緩衝中的結果
- $arrResult = include($cachFile);
- } else {
- $objPage = new Page_IndexModel($arrParams);
- $arrResult = $objPage->process();
- $strContent = "<?php \n return ".var_export($arrResult, true)."\n;";
-
- //將結果集緩衝
- file_put_contents($cachFile, $strContent);
- }
-
- //獲得結果後smarty賦值
- $smarty->assign($arrResult);
-
- //輸出模板
- $smarty->display();
參考來源:
PHP通過檔案儲存體來實現緩衝
http://www.lai18.com/content/407149.html