yii2.0主从数据库实现源码分析-----(二)

这篇主要是介绍当主或者从服务器挂掉之后,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>
                }
            }
        }


接着看下connection.php里面的一些属性

    /**
     * @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();




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值