私人领地

Swoft-Api项目部署八:主从数据库配置

手动档模式

手动模式需要xxx.com?db=1、xxx.com?db=2、xxx.com?db=3 这种方式来切换1、2、3数据库。操作权在用户手上。使用并不太方便。

手册地址:http://swoft.io/docs/2.x/zh-CN/db/selectDb.html

 

自动档模式:推荐使用

手册地址:http://swoft.io/docs/2.x/zh-CN/db/setting.html

1.bean配置

#不能写成db_rw
'db' => [
        'charset'  => 'utf8mb4',
        'prefix'   => 'z_',
        'config'   => [
            'collation' => 'utf8mb4_unicode_ci',
            'strict'    => true,
            'timezone'  => '+8:00',
            'modes'     => 'NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES'
        ],
        'writes' => [
            [
                'dsn'      => 'mysql:dbname=iot2com;host=127.0.0.1:3306',
                'username' => 'xxx',
                'password' => '123456',
            ]
        ],
        'reads'  => [
            [
                'dsn'      => 'mysql:dbname=iot2com1;host=127.0.0.1',
                'username' => 'xxx',
                'password' => '123456',
            ],
            [
                'dsn'      => 'mysql:dbname=iot2com2;host=127.0.0.1',
                'username' => 'xxx',
                'password' => '123456',
            ]
        ]
    ],

 

2.控制器调用

读:

/**
     * @RequestMapping()
     * */
    public function t30(Request $request){
        $result = DB::table('log_system')->first();
        print_r($result);
    }

每次刷新页面都显示不同数据,实现自动切换库,数据显示如下

 

 

 写:

/**
     * @RequestMapping()
     * */
    public function t33(){
        $data= [
           'title'=>'44444'
        ];
        $result = DB::table('log_system')->insert($data);
        print_r($result);
    }

自动插入主库iot2com

 

总结,自动档模式,配置好bean,在使用增、更、删 会自动切换到writes库,查会切换到reads库。完美实现切库动作

posted @ 2020-09-03 11:08  狂奔的蜗牛Snails  阅读(250)  评论(0编辑  收藏  举报