牛骨文教育服务平台(让学习变的简单)
博文笔记

Yii2数据库开启表结构缓存以及清除缓存

创建时间:2017-04-19 投稿人: 浏览次数:3392

Yii2开启表结构缓存,因为当运用模型(model)时,AR的一些公共属性都会从DB中获取,这样会导致服务器负担一些额外的资源开销,实际上对于成品来说,服务器这些开始销是多余的,故应该阻止这种默认行为,把表结构进行缓存起来,提高效率.Yii2的缓存值得深入研究学习.

开启数据库表结构的schema缓存的方法:

//配置文件的方式
"db"=>array(
    ...
    "enableSchemaCache" => true,
    "schemaCacheDuration" => 86400, // time in seconds
    ...
),
 
//区分环境--代码基类里面实现
$dsn = "mysql:host=" . $config["host"] . ":" . $config["port"] . ";dbname=" . $config["name"];
$connection = new Connection([
    "dsn" => $dsn,
    "username" => $config["user"],
    "password" => $config["password"]
]);
$connection->charset = "utf8mb4";
if(YII_ENV == "prod"){              //正式环境才开启
    $connection->enableSchemaCache = true;
}
//........
return $connection;


当开启了数据库的表结构缓存之后,需要改动或执行一些改变表结构的sql语句的时候,就会出现表结构被缓存了无法立即修复BUG或故障。这个时候就需要刷新或者清除数据库表结构的缓存信息。

//方法一:清空表结构缓存的方法
 
//flush all the schema cache
Yii::$app->db->schema->refresh();
 
//clear the particular table schema cache
Yii::$app->db->schema->refreshTableSchema($tableName);
 
 
//方法二:清空所有的缓存--不仅仅是mysql表结构
Yii::$app->cache->flush();
 
 
//方法三:使用 yii命令行的方式commond清除缓存
cache/flush                Flushes given cache components.
cache/flush-all            Flushes all caches registered in the system.
cache/flush-schema         Clears DB schema cache for a given connection component.
cache/index (default)      Lists the caches that can be flushed.
 
//执行 
./yii cache/flush-all


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。