跳至正文

Laravel框架读写分离测试

#配置修改
 'mysql' => [
            'read' => [
                'host' => '192.168.31.194',
            ],
            'write' => [
                'host' => '127.0.0.1',
            ],
            #同一请求周期内使用相同链接获取数据
            'sticky'    => true,
            'driver'    => 'mysql',
            'database'  => 'lara',
            'username'  => 'root',
            'password'  => '123456',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix'    => '',
  ],

测试代码

public function create()
    {
        dump(Order::count());
        $res = Order::create(['sn' => date('YmdHis') . mt_rand(0000, 9999)]);
        dump(Order::find($res->id), Order::count());
    }

stop slave; 关闭从库同步

sticky 为 false时

sticky 为 true时

写入之后的读取的count数为47 插入的id模型也打印成功,说明laravel在写入操作之后使用的是写连接.

源码分析

Illuminate\Database\Connection.php

/**
     * Get the current PDO connection used for reading.
     *
     * @return \PDO
     */
    public function getReadPdo()
    {
        if ($this->transactions > 0) {
            return $this->getPdo();
        }

        if ($this->getConfig('sticky') && $this->recordsModified) {
            return $this->getPdo();
        }

        if ($this->readPdo instanceof Closure) {
            return $this->readPdo = call_user_func($this->readPdo);
        }

        return $this->readPdo ?: $this->getPdo();
    }

代码判断配置sticky 为true 并且数据修改成功返回当当前链接