【问题标题】:How to flush db query cache in yii2?如何在 yii2 中刷新数据库查询缓存?
【发布时间】:2016-05-18 02:38:53
【问题描述】:

特定表记录发生变化时如何处理?

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;
        }

【问题讨论】:

  • 使用Delete()
  • 在数据库查询中我没有特定的键。像 Yii::$app->cache->delete($key);在我的例子中怎么做?
  • 为缓存设置特定键,然后调用 delete()。使用set()
  • 试试:Yii::$app->cache->set('dbCache', $result, 0, null)
  • 没有。它不工作。正如@SohelAhmedM 所建议的那样,它可以工作,但会删除所有缓存数据。

标签: yii2 query-cache


【解决方案1】:

对于全局缓存,可以使用:

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 示例,它提供了帮助。
【解决方案2】:

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

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

【讨论】:

  • 我会检查的。以及如果表特定记录发生任何变化如何处理?
  • 这也将删除我的整个缓存。我想专门针对数据库查询。
  • 这绝对不是解决方案,因为它会刷新你的整个缓存。这意味着查询缓存、rbac-cache、schema-cache 关于所有内容,除非您附加了多个缓存组件......
【解决方案3】:

您应该简单地使用\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;
}

Read more...

【讨论】:

  • 这应该被接受为答案,因为它是根据 yii2-specs 的正确解决方案!
  • 我想过这样做,但是 Yii 是如何知道数据何时发生变化的呢?要知道它是否必须进行查询才能找出并因此首先破坏缓存的目的!?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 2013-02-15
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
相关资源
最近更新 更多