常見現象
運維工作中會經常維護MySQL主從服務器,當然Slave我們只是用於讀操作。
一般權限開通也只授權只讀賬號,但是有時候維護工作可能不是一個人在做,你不能保證其他同事都按照這個標准操作。
有同事可能會授權Slave庫MySQL賬號為all或者select,update,insert,delete。還有一種情況是主從做了對所有數據的同步(包括用戶信息),在Master庫上面授權的賬號也同步到了Slave庫上面,當然Master賬號中肯定會有select,update,insert,delete權限。
存在的問題
那么問題來了,當運維人員或者開發人員程序錯誤的連接了Mysql把Slave當成了Master等情況,那么就悲催了所有的數據修改就到Slave了,也會直接影響到主從的同步。
為了避免上述問題,我們需要給MySQL的Slave設置為只讀模式。
解決方法
演示如下:
mysql> set global read_only=1;
Query OK, 0 rows affected (0.00 sec)
#set global read_only=0 為取消普通賬號的只讀模式
授權普通MySQL測試賬號
mysql> grant select,insert,update,delete on s18.* to 'test'@'127.0.0.1' identifi ed by '123456'; Query OK, 0 rows affected, 1 warning (0.00 sec)
用測試賬號登陸進行刪除等操作,會提示--read-only錯誤
mysql> delete from student where sid=14; ERROR 1290 (HY000): The MySQL server is running with the --read-only option so i t cannot execute this statement mysql> insert class values(5,三年級十班); ERROR 1290 (HY000): The MySQL server is running with the --read-only option so i t cannot execute this statement
注意:set global read_only=1 對擁有super權限的賬號是不生效的,所以在授權賬號的時候盡量避免添加super權限
那么我們在做數據遷移的時候不想發生任何數據的修改,包括super權限修改也要限制。
可以用鎖表:
mysql> flush tables with read lock; Query OK, 0 rows affected (0.18 sec)
使用root賬號測試:
mysql> delete from student where sid=13; ERROR 1223 (HY000): Can't execute the query because you have a conflicting read lock
解鎖測試:
mysql> unlock tables; Query OK, 0 rows affected (0.00 sec) mysql> delete from student where sid=13; Query OK, 0 rows affected (0.00 sec)