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缓存,最好缓存一些不那么占用内存的小且频繁使用的数据。对于一些频繁操作的数据,用文件缓存

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