如何在yii2中清除数据库查询缓存?

8
当特定表中的记录发生更改时,应如何处理?
public static function getAirportWithCache($iata_code){

              $result = Airports::getDb()->cache(function ($db) use ($iata_code){
                     $res = Airports::find()
                               ->where(['iata_code' => $iata_code])
                               ->limit(1)
                               ->asArray()
                               ->one();
                     return $res;
              });
              return $result;
        }

在数据库查询中,我没有特定的键。例如Yii::$app->cache->delete($key); 在我的例子中该怎么做? - Yatin Mistry
为缓存设置特定的键,然后调用delete()。使用set()。 - Insane Skull
不,它没有起作用。正如@SohelAhmedM建议的那样,它会起作用,但会删除所有缓存数据。 - Yatin Mistry
没有收到任何错误。 - Yatin Mistry
好的。我也在 yii2论坛 上提出了这个问题。 - Yatin Mistry
显示剩余8条评论
3个回答

14

全局缓存可以使用:

Yii::$app->cache->flush();

你可以使用TagDependency实现具体的功能:

 //way to use
return Yii::$app->db->cache(function(){
    $query =  new Query();
    return $query->all();
}, 0, new TagDependency(['tags'=>'cache_table_1']));

//way to flush when modify table
TagDependency::invalidate(Yii::$app->cache, 'cache_table_1');

请查看文档http://www.yiiframework.com/doc-2.0/yii-caching-tagdependency.html


感谢您提供的TagDependency示例,它对我很有帮助。 - MaxGhost

4
您应该简单地使用\yii\caching\DbDependency,例如:

public static function getAirportWithCache($iata_code){
    // for example if airports count change, this will update your cache
    $dependency = new \yii\caching\DbDependency(['sql' => 'SELECT COUNT(*) FROM ' . Airports::tableName()]);
    $result = Airports::getDb()->cache(function ($db) use ($iata_code){
        return Airports::find()
            ->where(['iata_code' => $iata_code])
            ->limit(1)
            ->asArray()
            ->one();
    }, 0, $dependency);
    return $result;
}

阅读更多...


1
根据yii2-specs,这应该被接受为答案,因为它是正确的解决方案! - PLM57
我曾考虑过这个问题,但 Yii 如何知道数据何时发生了更改呢?要知道这一点,它不得不执行查询以找出变化,这不就违背了缓存的初衷吗?! - Brett

2

只需在任何地方执行Yii::$app->cache->flush();(可能在您的控制器中)即可。

PS:它将删除存储在服务器上的整个缓存。


我会检查,如果表格中特定记录有任何更改如何处理? - Yatin Mistry
同时,这将删除我的整个缓存。我想要针对数据库查询进行特定的操作。 - Yatin Mistry
4
这绝对不是解决方案,因为它会清空你的整个缓存。这意味着查询缓存、rbac缓存、模式缓存等所有内容都将被清空,除非你有多个缓存组件附加... - PLM57

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接