yii2 db 單機配置
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=newplan',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'tablePrefix' => 's_',//前綴
]
...
配合mgr 多主配置 (本地docker 下起來3臺mysql 服務(wù)端組了mgr,如何組建mgr集群請看docker mysql mgr 集群)
'db' => [
'class' => 'yii\db\Connection',
'shuffleMasters' => true, // 隨機選擇數(shù)據(jù)庫鏈接
'masterConfig' => [
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'tablePrefix' => 's_',//前綴
'attributes' => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
],
],
'masters' => [
['dsn' => 'mysql:host=localhost;port=3306;dbname=newplan'],
['dsn' => 'mysql:host=localhost;port=3307;dbname=newplan'],
['dsn' => 'mysql:host=localhost;port=3308;dbname=newplan']
],
]
可能出現(xiàn)的報錯
-
yii2 None of the master DB servers is available極少數(shù)出現(xiàn),按照錯誤提示是沒有找到可以鏈接的主機, 首先排除當前配置的主機是非能夠鏈接的上,先使用但數(shù)據(jù)庫的配置鏈接查看是否有問題 -
Server sent charset unknown to the client. Please, report to the developers在我數(shù)據(jù)庫設(shè)置完成之后,使用yii鏈接單個數(shù)據(jù)庫做測試發(fā)現(xiàn)了這個錯誤,原因是:MySQL 8將默認字符集更改為utfmb4。但有些客戶并不知道這個規(guī)則。因此,當服務(wù)器向客戶端報告其默認字符集時,客戶端不知道服務(wù)器是什么意思,就會拋出此錯誤。
解決方案,修改mysql配置加上:
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8
default_authentication_plugin = mysql_native_password
3.注意,如果集群中有mysql節(jié)點出現(xiàn)故障下線,雖然yii自己會處理不去連接故障服務(wù)器,但是故障處理完成的時候要小心,如果你的mgr集群沒有開啟 loose-group_replication_start_on_boot=ON #是否隨服務(wù)器啟動而自動啟動組復(fù)制 的話,當你的mysql回復(fù)正常能夠正常連接,yii 有可能連上這臺沒有加入集群沒有開啟組復(fù)制的mysql節(jié)點,這個節(jié)點是沒有寫入能力的(super_read_only),所以寫入操作會導(dǎo)致報錯(mgr的機制),
解決方案:
1.因為不是很建議loose-group_replication_start_on_boot開啟,所以在集群節(jié)點發(fā)生故障下線的時候,直到節(jié)點恢復(fù)加入集群之前,都先將配置文件中的該節(jié)點去除。
2.開啟loose-group_replication_start_on_boot