laravel学习:主从读写分离配置的实现

本篇文章给大家带来的内容是关于laravel学习:主从读写分离配置的实现,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

在db的连接工厂中找到以下代码
…/vendor/laravel/framework/src/illuminate/database/connectors/connectionfactory.php

/**  * Get the read configuration for a read / write connection.  *  * @param  array  $config  * @return array  */  protected function getReadConfig(array $config)  {      $readConfig = $this->getReadWriteConfig($config, 'read');            return $this->mergeReadWriteConfig($config, $readConfig);  }    /**  * Get a read / write level configuration.  *  * @param  array   $config  * @param  string  $type  * @return array  */  protected function getReadWriteConfig(array $config, $type)  {      if (isset($config[$type][0])) {          return $config[$type][array_rand($config[$type])];      }        return $config[$type];  } /** * Merge a configuration for a read / write connection. * * @param  array  $config * @param  array  $merge * @return array */protected function mergeReadWriteConfig(array $config, array $merge){    return array_except(array_merge($config, $merge), ['read', 'write']);}

工厂类通过随机获取读DB配置来进行读取操作,由此可推出DB的配置应该如下

'mysql' => [      'write'    => [          'host' => '192.168.1.180',      ],      'read'     => [          ['host' => '192.168.1.182'],          ['host' => '192.168.1.179'],      ],      'driver'    => 'mysql',      'database'  => 'database',      'username'  => 'root',      'password'  => '',      'charset'   => 'utf8',      'collation' => 'utf8_unicode_ci',      'prefix'    => '', ]

加强版,支持多主多从,支持独立用户名和密码,配置如下

'mysql' => [      'write'    => [          [            'host' => '192.168.1.180',            'username'  => '',            'password'  => '',        ],      ],      'read'     => [          [            'host' => '192.168.1.182',            'username'  => '',            'password'  => '',        ],          [            'host' => '192.168.1.179',            'username'  => '',            'password'  => '',        ],      ],      'driver'    => 'mysql',      'database'  => 'database',         'charset'   => 'utf8',      'collation' => 'utf8_unicode_ci',      'prefix'    => '', ]

验证
开启MySQL的general-log,通过tail -f的方式监控log变化来确定配置是否生效

相关文章推荐:

立即进入“豆包AI人工智官网入口”;

立即学习“豆包AI人工智能在线问答入口”;

Laravel的功能测试:测试驱动开发(附代码)

以上就是laravel学习:主从读写分离配置的实现的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/113036.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
win11如何开启或关闭卓越性能模式 win11卓越性能模式开启关闭教程
上一篇 2025年11月24日 01:00:54
《忍者龙剑传4》1.1小时试玩视频 龙隼一开始就可操作
下一篇 2025年11月24日 01:02:56

相关推荐

发表回复

登录后才能评论
关注微信