super_read_only和read_only参数共同控制数据库的读写状态,用于控制管理员、普通用户的写入权限。
本文基于MySQL8.4.3版本。MySQL8.4官方参考手册:
https://dev.mysql.com/doc/refman/8.4/en/server-system-variables.html#sysvar_super_read_only
https://dev.mysql.com/doc/refman/8.4/en/server-system-variables.html#sysvar_read_only
super_read_only
默认值OFF,适用于主从切换、故障恢复场景中,临时设置super_read_only = ON可以防止管理员误操作导致数据不一致。也适用于高安全性要求的从库上,禁止任何用户在从库上写入,也适用于维护的场景等。
临时生效
1 |
SET GLOBAL super_read_only = ON; |
永久生效修改MySQL配置文件以下参数
1 |
super_read_only = ON |
查看当前状态
1 |
SHOW VARIABLES LIKE 'super_read_only'; |
read_only
默认值OFF,适用于主从复制中,从库设置为read_only = ON,防止应用程序误写入从库,避免数据不一致。
临时生效
1 |
SET GLOBAL read_only = ON; |
永久生效修改MySQL配置文件以下参数
1 |
read_only = ON |
查看当前状态
1 |
SHOW VARIABLES LIKE 'read_only'; |
演示示例
通过root管理员创建普通用户
1 2 |
CREATE USER 'wh'@'%' IDENTIFIED BY 'wh'; GRANT SELECT, INSERT, CREATE ON *.* TO 'wh'@'%'; |
1、修改my.cnf,设置super_read_only=OFF、read_only=ON
1 2 |
mysql -uroot -p create database wh1; |
Query OK, 1 row affected (0.01 sec)
使用管理员用户执行写入操作,写入成功。
1 2 |
mysql -uwh -p create database wh2; |
ERROR 1290 (HY000): The MySQL server is running with the --read-only option so it cannot execute this statement
使用普通用户执行写入操作,写入失败。
2、修改my.cnf,设置super_read_only=ON、read_only=ON
1 2 |
mysql -uroot -p create database wh2; |
ERROR 1290 (HY000): The MySQL server is running with the --super-read-only option so it cannot execute this statement
使用管理员用户执行写入操作,写入失败。
1 2 |
mysql -uwh -p create database wh2; |
ERROR 1290 (HY000): The MySQL server is running with the --read-only option so it cannot execute this statement
使用普通用户执行写入操作,写入失败。
3、修改my.cnf,设置super_read_only=ON、read_only=OFF
1 2 |
mysql -uroot -p create database wh2; |
ERROR 1290 (HY000): The MySQL server is running with the --super-read-only option so it cannot execute this statement
使用管理员用户执行写入操作,写入失败。
1 2 |
mysql -uwh -p create database wh2; |
ERROR 1290 (HY000): The MySQL server is running with the --read-only option so it cannot execute this statement
使用普通用户执行写入操作,写入失败。
总结
当super_read_only=OFF、read_only=OFF时,此时管理员、普通用户均有写入权限。
当super_read_only=OFF、read_only=ON时,此时管理员有写入权限,普通用户无写入权限。
当super_read_only=ON时,未配置read_only参数时,read_only隐式为ON,即read_only=ON,此时管理员、普通用户均无写入权限。
当super_read_only=ON时,设置read_only=OFF时,此时管理员、普通用户均无写入权限。
附,MySQL my.cnf配置文件生成器:https://dbcnf.wlnmp.com/
原文链接:MySQL super_read_only和read_only参数介绍,转载请注明来源!