yii2数据库配置一主多从和多主多从
全文约 229 字预计阅读 1 分钟
yii2配置文件如下:
[ 'class' => 'yii\db\Connection', // common configuration for masters 'masterConfig' => [ 'username' => 'master', 'password' => '', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], ], // list of master configurations 'masters' => [ ['dsn' => 'dsn for master server 1'], ['dsn' => 'dsn for master server 2'], ], // common configuration for slaves 'slaveConfig' => [ 'username' => 'slave', 'password' => '', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], ], // list of slave configurations 'slaves' => [ ['dsn' => 'dsn for slave server 1'], ['dsn' => 'dsn for slave server 2'], ['dsn' => 'dsn for slave server 3'], ['dsn' => 'dsn for slave server 4'], ], ]protected function openFromPool(array $pool, array $sharedConfig) { if (empty($pool)) { return null; } if (!isset($sharedConfig['class'])) { $sharedConfig['class'] = get_class($this); } $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache; shuffle($pool);//源码这里随机读取配置 foreach ($pool as $config) { $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)) { // 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); } } } return null; }
yii2数据库配置一主多从和多主多从
评论 0 条
暂无评论,来说点什么吧。