LUMEN框架多数据库连接配置方法

LUMEN作为一款API导向很浓的框架,配置极简化,默认只支持一路DB配置

然而随着业务复杂度的提高,引入多个数据库连接似乎无法避免,下面介绍一下LUMEN连接多个数据库的配置方法:

  • 修改.env文件,增加新DB配置,如下:
//DB1 配置

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=dbname

DB_USERNAME=dbname

DB_PASSWORD=password

DB_TIMEOUT=4

//DB2配置

DB_TEST_CONNECTION=mysql

DB_TEST_HOST=127.0.0.1

DB_TEST_PORT=3307

DB_TEST_DATABASE=dbname2

DB_TEST_USERNAME=dbname2

DB_TEST_PASSWORD=password

DB_TEST_TIMEOUT=4
  • 因为LUMEN在加载DB配置时,还是会默认去laravel模块下寻找相关配置文件,这时修改laravel模块下的database.php文件
    文件位置在:
    ./vendor/laravel/lumen-framework/config/database.php
    添加.env文件中新增的DB配置,如下:
//默认配置
        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'port'      => env('DB_PORT', 3306),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => env('DB_CHARSET', 'utf8'),
            'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
            'prefix'    => env('DB_PREFIX', ''),
            'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],

//新增配置
        'mysql_test'=>[
            'driver'    => 'mysql',
            'host'      => env('DB_TEST_HOST', 'localhost'),
            'port'      => env('DB_TEST_PORT', 3306),
            'database'  => env('DB_TEST_DATABASE', 'forge'),
            'username'  => env('DB_TEST_USERNAME', 'forge'),
            'password'  => env('DB_TEST_PASSWORD', ''),
            'charset'   => env('DB_CHARSET', 'utf8'),
            'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
            'prefix'    => env('DB_PREFIX', ''),
            'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],

  • 在项目中调用时,直接按database.php中的做法初始化connection就行,如下:
$query = app('db')->connection("mysql_test")->select("...");

你可能感兴趣的:(LUMEN框架多数据库连接配置方法)