概述
传统使用mysqldump方式每天定时备份,一是备份的时候整个数据库锁表,二是数据不安全性,有可能导致数据备份不及时而丢失数据。
mysql主从复制,就为解决此2个问题,同时更多的是带来性能和开发模式的改变,
压力有效分解到从服务器,具体怎么安装mysql 主从或者主主这里不描述,讲一个php(yii2)实践。
yii2安装主从:
参考文档:http://www.yiiframework.com/doc-2.0/guide-db-dao.html#read-write-splitting
修改项目目录下的config/main-local.php,
会覆盖common/main-local.php 的 db配置
'db'=>[ 'class' => 'yii\db\Connection', 'charset' => 'utf8', // configuration for the master 'dsn' => 'mysql:host=dbhost;dbname=test', 'username' => '', 'password' => '', // common configuration for slaves 'slaveConfig' => [ 'username' => '', 'password' => '', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], 'charset' => 'utf8', ], // list of slave configurations 'slaves' => [ ['dsn' => 'mysql:host=dbhost;dbname=test'], ], ],
更改dsn和username、password,默认数据库读在slave服务器,写在master。
事务性读写都在master。
存在的问题:
主从默认的读写方式有时候会造成脏数据,比如从服务器同步延迟,读从服务器没有数据,一直向主服务器写入数据。最好的办法是制定是读master 还是slave。
在不适用主从这种读写方式,可以使用多数据库。
'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=;dbname=', 'username' => '', 'password' => '', 'charset' => 'utf8', ], 'db2' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=;dbname=', 'username' => '', 'password' => '', 'charset' => 'utf8', ],
这个方式更为灵活,配合主从数据库混合使用
$db = Yii::$app->db; $db2 = Yii::$app->db2;
Comments are closed.