«
Laravel配置Mysql读写分离

时间:2021-7-17    作者:网络剑客    分类: php


修改config/database.config文件:

'mysql' => [
    'driver' => 'mysql',
    'read' => [ // 读库配置
    'host' => env('DB_READ_HOST', '127.0.0.1'),
    'username' => env('DB_READ_USERNAME', ''),
    'password' => env('DB_READ_PASSWORD', ''),
    'port' => env('DB_READ_PORT', 3308),
    ],
    'write' => [ // 写库配置
    'host' => env('DB_WRITE_HOST', '127.0.0.1'),
    'username' => env('DB_WRITE_USERNAME', ''),
    'password' =>  env('DB_WRITE_PASSWORD', ''),
    'port' => env('DB_WRITE_PORT', 3307)
    ],
    // 'host' => env('DB_HOST', '127.0.0.1'),
    // 'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    //'username' => env('DB_USERNAME', 'forge'),
    // 'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => env('DB_CHARSET', 'utf8mb4'),
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => env('DB_PREFIX', ''),
    'strict' => true,
    'engine' => null,
],

修改.env文件

DB_CONNECTION=mysql

DB_READ_HOST=127.0.0.1
DB_READ_PORT=3308
DB_READ_USERNAME=root
DB_READ_PASSWORD=123456

DB_WRITE_HOST=127.0.0.1
DB_WRITE_PORT=3307
DB_WRITE_USERNAME=root
DB_WRITE_PASSWORD=123456

DB_PREFIX=cy_
DB_CHARSET=utf8mb4
DB_DATABASE=cyshop

如要配置一写多读/多读多写,仅需将read/write数组中的值改为数组, 如

'read' => [
  ['host'=> env('DB_READ_HOST_TWO'), ]
],
'write => [
    ['host'=> env('DB_WRITE_HOST_TWO'), ]
],

标签: laravel