**
**
随着项目用户量、访问量的增长,对数据库进行读写分离可以有效的提升应用整体性能
记录下如何在 Laravel 中操作数据库。
不同的数据库来进行读写分离,在数据库中创建一个新的数据库用作写数据库,并将其配置到 config/database.php:
'mysql' => [
'driver' => 'mysql',
'read' => [
'host' => env('DB_HOST_READ', '127.0.0.1'),
'database' => env('DB_DATABASE', 'ht_read'),
],
'write' => [
'host' => env('DB_HOST_WRITE', '127.0.0.1'),
'database' => env('DB_DATABASE_WRITE', 'ht_write'),
],
'port' => env('DB_PORT', '3306'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
连接双库这个因为目前的项目算是中等偏上的项目,而且还跟其他项目进行了打通融合,导致需要查询两个不同的数据库。配置两个数据库连接就行也比较简单:
config/database.php:
//第一个数据库
'mysql' => [
'driver' => 'mysql',
'read' => [
'host' => env('DB_HOST_READ', '127.0.0.1'),
'database' => env('DB_DATABASE', 'ht_read'),
],
'write' => [
'host' => env('DB_HOST_WRITE', '127.0.0.1'),
'database' => env('DB_DATABASE_WRITE', 'ht_write'),
],
'port' => env('DB_PORT', '3306'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
// 第二个数据库
'mysql_saas' => [
'driver' => 'mysql',
'read' => [
'host' => env('DB_HOST_READ', '127.0.0.1'),
'database' => env('DB_DATABASE', 'saas_read'),
],
'write' => [
'host' => env('DB_HOST_WRITE', '127.0.0.1'),
'database' => env('DB_DATABASE_WRITE', 'saas_write'),
],
'port' => env('DB_PORT', '3306'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
查询的时候在自己项目的BaseModel里边指定数据库连接名就可以了
// 第一个库默认就是mysql所以第一个可以不用配置此项
class BaseModel extends Model
{
protected $connection = 'mysql';
}
// 第二个库
class BaseModel extends Model
{
protected $connection = 'mysql_saas';
}