Yii2 memcached不缓存数据

时间:2019-03-01 08:25:40

标签: yii2

我由我创建了这个课程:

<?php
/**
 * Created by PhpStorm.
 * User: Dell
 * Date: 28.2.2019 г.
 * Time: 11:36
 */

namespace common\components;


use yii\caching\CacheInterface;

class Cache
{
    /* @var \yii\caching\CacheInterface */
    private $cache;

    public function __construct()
    {
        $this->cache = \Yii::$app->cache;
    }

    /**
     * Cache data. If key exists - retrieve data.
     * If app cache is disabled - return passed data without any processing
     * @param $key
     * @param $data
     * @param null $duration
     * @param null $dependency
     * @return mixed
     */
    public function getOrSet($key, $data, $duration = null, $dependency = null)
    {
        if ($this->isCacheEnabled()) {
            return $this->cache->getOrSet($key, function () use ($data) {
                return $data;
            }, $duration, $dependency);
        }
        return $data;
    }

    /**
     * Retrieve cache object
     */
    public function getCache(): CacheInterface
    {
        return $this->cache;
    }

    /**
     * Check weather the cache is enabled or not
     */
    public function isCacheEnabled(): bool
    {
        return $this->cache ? true : false;
    }
}

现在,当尝试缓存诸如以下内容时:

$cache = new Cache();
$data = $cache->getOrSet("somekey", "somedata");

如果我在如下视图文件中这样做:

$cache = Yii::$app->cache;
if ($cache->exists("somekey")) {
   $data = $cache->get("somekey");
} else {
   $data = $cache->set("somekey", "somedata")
}

工作正常。我在Yii2调试工具中有所作为,在该工具中,数据库请求在第一个版本中(与我的班级一样)下降到600个,而在第二个版本中,我直接通过Yii2 memcached完成它的请求下降到500个。我是否检查正确,为什么这些变体之间有区别? 谢谢!

0 个答案:

没有答案