CodeIgniter的緩存小記


 

    最近接觸到了CodeIgniter開源輕量級架構,集合了開發中常用的類和功能函數,關於CodeIgniter的緩存總結有以下幾點:

    1. 數據庫緩存

    數據庫緩存主要是針對於SELECT查詢

// 打開緩存開關
$this->db->cache_on();
$query1 = $this->db->query("SELECT * FROM mytable");

// 使下面這條查詢不被緩存
$this->db->cache_off();
$query2 = $this->db->query("SELECT * FROM members WHERE member_id = '$current_user'");

// 再次打開緩存開關
$this->db->cache_on();
$query3 = $this->db->query("SELECT * FROM another_table");

      這樣query1和query3就被緩存在文件中了,緩存的路徑根據您的URL而定,如example.com/index.php/blog/comments的頁面, 緩存系統會把所有生成的緩存文件放進一個以 blog+comments做為名稱的文件夾里. 如果您要刪除關於剛才提到的這個例子與之對應的緩存文件 需要執行以下代碼:

$this->db->cache_delete('blog', 'comments');//$this->db->cache_delete('blog', 'comments')#來刪除緩存

     如果要清除所有數據庫緩存:

$this->db->cache_delete_all();

    *其cache模式在於針對不同的uri就會生成cache文件,如果URL中參數不同,則 cache文件就會不同,從而產生了漏洞。如果訪問者構建自動生成URI,不斷向服務器發起請求,就會瞬間產生大量的垃圾文件,導致系統文件臃腫。

    2. 頁面緩存

$this->output->cache(n); // 請確保application/cache可寫

     n 是你希望緩存更新的 分鍾 數。可以使用 m/60 來精確到秒,例如 1/60 ,則是精確到 1秒
  

    3. 序例化緩存到文件

$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));

if ( ! $foo = $this->cache->get('foo'))
{
echo 'Saving to the cache!<br />';
$foo = 'foobarbaz!';

// Save into the cache for 5 minutes
$this->cache->save('foo', $foo, 300);
}

echo $foo;

    延伸閱讀:http://codeigniter.org.cn/user_guide/drivers/caching.html

                  http://justcoding.iteye.com/blog/657357


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM