读写分离:让主数据库(master)处理事务性增、改、删操作(INSERT、UPDATE、DELETE),而从数据库 (slave)处理SELECT查询操作。
修改db.php的配置
一主多从
<?php return [ 'class' => 'yii\db\Connection',//class指向yii\db\Connection 'dsn' => 'mysql:host=41.21.111.120;dbname=yayuting_test', 'username' => 'root', 'password' => '123', 'charset' => 'utf8', 'slaveConfig' =>[ 'username' => 'root', 'password' => '123', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ] ], 'slaves' =>[ ['dsn'=>'mysql:host= 41.21.111.120; dbname=yayuting_slave1'], ['dsn'=>'mysql:host= 41.21.111.120; dbname=yayuting_slave2'] ] ];
<?php
namespace app\controllers;
use app\models\BasicUser;use yii\web\Controller; use app\models\UserForm; use yii\web\Response; class UserController extends Controller{public function actionSlave(){ $db=\yii::$app->db; //获得数据库对象$cmd=$db->createCommand('SELECT * FROM test where id=1');$res=$cmd->queryAll();echo json_encode($res,JSON_UNESCAPED_UNICODE); } }
优势: 1.从库负载均衡
2.故障自动摘除
多主多从:
优势: 1.从库负载均衡
2.故障自动摘除
3.主库负载均衡
4.强制读主库