【发布时间】:2015-05-26 13:29:17
【问题描述】:
所以我一直在尝试让 memcache 在我的运行 Yii 2 的网站上工作。我已经为 DB 模式的东西工作了缓存,但它似乎不适用于 ActiveRecord 查询。
这是我的数据库配置:
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=db_name',
'username' => 'user_name',
'password' => 'password',
'charset' => 'utf8',
'enableQueryCache' => true,
'queryCache' => 'cache',
'queryCacheDuration' => 600,
'enableSchemaCache' => true,
'schemaCache' => 'cache',
'schemaCacheDuration' => 3600,
]
根据指南 (http://www.yiiframework.com/doc-2.0/guide-caching-data.htm),这应该足以让全局缓存正常工作。据我了解,如果设置了这些变量,那么它应该在指定的时间内缓存所有查询,还是我仍然需要专门调用 if ?
$result = Customer::getDb()->cache(function ($db) {
return Customer::find()->where(['id' => 1])->one();
});
我深入研究了代码库以查看发生了什么,它看起来像 \yii\db\Connection::getQueryCacheInfo() 被更改为如下所示:它会完美运行:
public function getQueryCacheInfo($duration, $dependency)
{
if (!$this->enableQueryCache) {
return null;
}
$duration = (isset($duration)) ? $duration : $this->queryCacheDuration;
$dependency = (isset($dependency)) ? $dependency : $this->queryCache;
我在这里做错了吗?为什么我不能让所有查询默认使用 memcache?
谢谢
【问题讨论】:
-
仅供参考:
return Customer::findOne(1);也可以。 -
@Blizz,是的,这只是 Yii 文档的复制粘贴。