这篇主要是介绍当主或者从服务器挂掉之后,yii的处理
connection.php
$cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;<span style="color:#ff0000;">//获取配置文件中的cache</span>
shuffle($pool);
foreach ($pool as $config) {<span style="color:#ff0000;">//遍历数据库配置项,从这里也看出来了,再配置数据库的时候,一般masters/slaves是个二维数组,而config是一维的用来共享</span>
$config = array_merge($sharedConfig, $config);
if (empty($config['dsn'])) {
throw new InvalidConfigException('The "dsn" option must be specified.');
}
$key = [__METHOD__, $config['dsn']];
if ($cache instanceof Cache && $cache->get($key)) {<span style="color:#ff0000;">//会先判断cache里面是否有$key,有$key说明这个库连接失败过,而且还没过那个时间</span>
// should not try this dead server now
continue;
}
/* @var $db Connection */
$db = Yii::createObject($config);
try {
$db->open();
return $db;
} catch (\Exception $e) {
Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
if ($cache instanceof Cache) {
// mark this server as dead and only retry it after the specified interval
$cache->set($key, 1, $this->serverRetryInterval);<span style="color:#ff0000;">//初始化PDO失败,写入缓存记录,有效期是$this->serverRetryInterval</span>
}
}
}
/**
* @var Cache|string the cache object or the ID of the cache application component that is used to store
* the health status of the DB servers specified in [[masters]] and [[slaves]].
* This is used only when read/write splitting is enabled or [[masters]] is not empty.
*/
public $serverStatusCache = 'cache';<span style="color:#ff0000;">//缓存,存放标志位</span>
/**
* @var integer the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
* This is used together with [[serverStatusCache]].
*/
public $serverRetryInterval = 600;<span style="color:#ff0000;">//时间,过多久之后才会重试之前宕掉的数据库服务器</span>
在main.php中
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',<span style="color:#ff0000;">//默认的缓存配置</span>
],
],
];
从上面的源码中可以看出来,每次请求到来,yii初始化PDO的时候,对于上次宕掉的数据库服务器,采用了标志位避免了轮询,而是每隔一定的时间,来初始化
清除缓存的方法
$cache=Yii::$app->get("cache");
$cache->flush();