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("...");
 
 


作者:天凌
链接:https://www.jianshu.com/p/7ab1029ee543
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2020-04-21 11:23  brady-wang  阅读(1347)  评论(0编辑  收藏  举报