Yii2 使用緩存

Yii2 使用緩存

配置

common\config\main.php

'components' => [
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
],

默認的緩存數據被存儲在各個應用的 runtime/cache 目錄,我們可以通過 FileCache的cachePath進行修改。

使用

通過 Yii::$app->cache 的方法調用

$cache = Yii::$app->cache;
// 從緩存中取回 $data 
$data = $cache->get($key);
if ($data === false) {
    // $data 在緩存中沒有找到,則重新獲取這個值
    $data = "獲取數據或者直接設置數據值";
    // 將 $data 存放到緩存供下次使用
    $cache->set($key, $data);
}

簡單的分析:

1. 首先程序會通過Yii::$app->cache->get方法獲取數據。
2. key的形式支持數組和字符串,對於一些複雜的業務。
3. 如果沒獲取到有效的數據,get方法會返回false,嚴謹起見使用 === 判斷。
4. 如果沒獲取到有效的數據,可以獲取或者設置,然後再通過程序處理之後通過Yii::$app->cache->set方法存儲。

在最新的2.0.11版本中,yii封裝了一個getOrSet方法

/**
     * Method combines both [[set()]] and [[get()]] methods to retrieve value identified by a $key,
     * or to store the result of $callable execution if there is no cache available for the $key.
     *
     * Usage example:
     *
     * ```php
     * public function getTopProducts($count = 10) {
     *     $cache = $this->cache; // Could be Yii::$app->cache
     *     return $cache->getOrSet(['top-n-products', 'n' => $count], function ($cache) use ($count) {
     *         return Products::find()->mostPopular()->limit($count)->all();
     *     }, 1000);
     * }
     * ```
     *
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
     * a complex data structure consisting of factors representing the key.
     * @param callable|\Closure $callable the callable or closure that will be used to generate a value to be cached.
     * In case $callable returns `false`, the value will not be cached.
     * @param int $duration default duration in seconds before the cache will expire. If not set,
     * [[defaultDuration]] value will be used.
     * @param Dependency $dependency dependency of the cached item. If the dependency changes,
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
     * This parameter is ignored if [[serializer]] is `false`.
     * @return mixed result of $callable execution
     */
    public function getOrSet($key, $callable, $duration = null, $dependency = null);
  • $callable是一個閉包
  • $duration是緩存的有效期,以秒爲單位
// 這裏的有效期是從程序執行的時候開始,填寫一個整數即可,比如我有一個數據要緩存1天,那就是
$cache->set($key, $data, 24*3600);
// 而不可以寫成
$cache->set($key, $data, time() + 24*3600);

默認該參數的值是0,即沒有有效期,除非有新的緩存覆蓋了之前的數據或者人爲刪除等操作。

  • $dependency是緩存依賴

假設有多個數據緩存項都緩存了某個用戶的相關的數據,當用戶信息修改之後,可以讓所有依賴這個用戶id的緩存項都失效,這便是set的最後一個參數緩存依賴的含義。

緩存依賴示例:

數據緩存的使用
use yii\caching\TagDependency;
Yii::$app->cache->set('user_10_profile', $profile, 0, new TagDependency(['tags' => 'user-10']));
Yii::$app->cache->set('user_10_stats', $stats, 0, new TagDependency(['tags' => 'user-10']));
想讓緩存失效,只需要調用緩存介質的invalidate方法即可
\yii\caching\TagDependency::invalidate(Yii::$app->cache, 'user-10');

除了TagDependency,還有下面這些你也可以使用

yii\caching\ChainedDependency:如果依賴鏈上任何一個依賴產生變化,則緩存失效

yii\caching\DbDependency:如果指定 SQL 語句的查詢結果發生了變化,則緩存失效

yii\caching\ExpressionDependency:如果指定的 PHP 表達式執行結果發生變化,則緩存失效

yii\caching\FileDependency:如果文件的最後修改時間發生變化,則緩存失效

最後,如果你是用的是內存比如memcache、redis緩存,最好緩存一些不那麼佔用內存的小且頻繁使用的數據。對於一些頻繁操作的數據,用文件緩存

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章