首頁 > php框架 > Laravel > 主體

laravel學習:主從讀寫分離配置的實現

不言
發布: 2018-08-08 16:16:24
原創
3279 人瀏覽過

這篇文章帶給大家的內容是關於laravel學習:主從讀寫分離配置的實現,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

在DB的連線工廠中找到以下程式碼
.../vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php

/** 
 * Get the read configuration for a read / write connection. 
 * 
 * @param  array  $config 
 * @return array 
 */  
protected function getReadConfig(array $config)  
{  
    $readConfig = $this->getReadWriteConfig($config, 'read');  
      
    return $this->mergeReadWriteConfig($config, $readConfig);  
}  
  
/** 
 * Get a read / write level configuration. 
 * 
 * @param  array   $config 
 * @param  string  $type 
 * @return array 
 */  
protected function getReadWriteConfig(array $config, $type)  
{  
    if (isset($config[$type][0])) {  
        return $config[$type][array_rand($config[$type])];  
    }  
  
    return $config[$type];  
} 

/**
 * Merge a configuration for a read / write connection.
 *
 * @param  array  $config
 * @param  array  $merge
 * @return array
 */
protected function mergeReadWriteConfig(array $config, array $merge)
{
    return array_except(array_merge($config, $merge), ['read', 'write']);
}
登入後複製

工廠類別透過隨機取得讀取DB配置來進行讀取操作,由此可推出DB的配置應該如下

'mysql' => [  
    'write'    => [  
        'host' => '192.168.1.180',  
    ],  
    'read'     => [  
        ['host' => '192.168.1.182'],  
        ['host' => '192.168.1.179'],  
    ],  
    'driver'    => 'mysql',  
    'database'  => 'database',  
    'username'  => 'root',  
    'password'  => '',  
    'charset'   => 'utf8',  
    'collation' => 'utf8_unicode_ci',  
    'prefix'    => '', 
]
登入後複製

加強版,支援多主多從,支援獨立使用者名稱和密碼,設定如下

'mysql' => [  
    'write'    => [  
        [
            'host' => '192.168.1.180',
            'username'  => '',
            'password'  => '',
        ],  
    ],  
    'read'     => [  
        [
            'host' => '192.168.1.182',
            'username'  => '',
            'password'  => '',
        ],  
        [
            'host' => '192.168.1.179',
            'username'  => '',
            'password'  => '',
        ],  
    ],  
    'driver'    => 'mysql',  
    'database'  => 'database',     
    'charset'   => 'utf8',  
    'collation' => 'utf8_unicode_ci',  
    'prefix'    => '', 
]
登入後複製

驗證
#開啟MySQL的general-log,透過tail -f的方式監控log變更來決定設定是否生效

相關文章推薦:

Laravel的功能測試:測試驅動開發(附程式碼)

以上是laravel學習:主從讀寫分離配置的實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!