Yii - 数据库依赖性缓存是否跨多个操作工作?

时间:2012-11-04 10:30:49

标签: caching yii

以这段代码为例:

public function actionPostOneWay( $postId )
{
    $dependency = new CDbCacheDependency( 'SELECT publish_date FROM posts WHERE id = :post_id;' );
    $dependency->params = array( 'post_id'=>$postId );
    $post = Post::model()->cache( 59, $dependency )->findByPk( $postId );

    // process post one way
}

public function actionPostAnotherWay( $postId )
{
    $dependency = new CDbCacheDependency( 'SELECT publish_date FROM posts WHERE id = :post_id;' );
    $dependency->params = array( 'post_id'=>$postId );
    $post = Post::model()->cache( 59, $dependency )->findByPk( $postId );

    // process post another way
}

那么访问/postOneWay/postAnotherWay会重用相同的缓存对象,还是会创建自己的缓存对象?

1 个答案:

答案 0 :(得分:5)

我尝试在两个不同的操作中缓存相同的查询,是的,将使用相同的缓存对象。可以看到在应用程序的配置文件中启用CProfileLogRoute

查看CActiveRecord类的源代码,我说public function findByPk($pk,$condition='',$params=array())方法(和其他查询方法)使用protected function query($criteria,$all=false)。反过来,这一个最终依赖于private function queryInternal($method,$mode,$params=array()) CDbCommand类,其中Yii使用数据库查询进行缓存。

正如可以看到用于存储和恢复查询的缓存密钥的结果定义如下:

$cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
$cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
if(($result=$cache->get($cacheKey))!==false)
{
    Yii::trace('Query result found in cache','system.db.CDbCommand');
    return $result;
}

此密钥不考虑缓存依赖项实例。 CDbCacheDependency仅用于确定数据库中是否更改了某些内容,并且要执行新查询以更新缓存。更多 - 如果您在两个操作中指定不同的SQL来创建CDbCacheDependency,则由于CDbCacheDependency的实例被缓存序列化以及查询结果,因此在缓存时间中只有一个(先执行)将有意义:

if(isset($cache,$cacheKey))
    $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);

public function set($id,$value,$expire=0,$dependency=null)类的CCache方法中可以看到缓存已评估依赖项的实例:

if ($dependency !== null && $this->serializer !== false)
    $dependency->evaluateDependency();

if ($this->serializer === null)
    $value = serialize(array($value,$dependency));
elseif ($this->serializer !== false)
    $value = call_user_func($this->serializer[0], array($value,$dependency));