从 MySQL 5.7 开始,binlog-ignore-db 的优先级高于 binlog-do-db。这意味着即使某个数据库被 binlog-do-db 指定,如果它同时出现在 binlog-ignore-db 的列表中,那么它的更改将不会被记录到二进制日志中
重启MySQL服务器。
复制代码
systemctl restart mysql
(追求安全,否则可跳过)登录MySQL数据库,创建远程连接的账号,并授予主从复制权限。
复制代码
# 创建xx用户,并设置密码,该用户可在任意主机连接该MySQL服务
create usxx'@'%' identified with mysql_native_password by 'xx1234';
# 为'xx'@'%'用户分配主从复制权限
grant replication slave on *.* to 'zking'@'%';
change master to master_host='xxx.xxx.xxx.xxx',master_user='xxx',master_password='xxx',master_log_file='xxx',master_log_pos=xxx;
change master to master_host='192.168.111.135',master_user='root',master_password='123',master_log_file='mysql_bin.000008',master_log_pos=2756;
MySQL8.0.23之后的版本,执行如下SQL语句:
复制代码
change replication source to source_host='xxx.xxx.xxx.xxx',source_user='xxx',source_password='xxx',source_log_file='xxx',source_log_pos=xxx;
参数说明:
参数名
含义
8.0.23之前
source_host
主库IP地址
master_host
source_user
连接主库的用户名
master_user
source_password
连接主库的密码
master_password
source_log_file
binlog日志文件名
master_log_file
source_log_pos
binlong日志文件位置
master_log_pos
4)开启同步操作
复制代码
# 8.0.22之后
start replica;
# 8.0.22之前
start slave;
5)查看主从同步状态
复制代码
# 8.0.22之后
show replica status;
# 8.0.22之前
show slave status;
# 切换数据库
use db1;
# 创建数据表t_student
create table t_student(sid int primary key auto_increment,sname varchar(20) not null,sage int default 0,ssex varchar(2) default '1');
# 批量添加数据
insert into t_student(sname,sage,ssex) values('张三',26,'男'),('王五',22,'女'),('小七',23,'女');
2)登录从库MySQL,查看主从复制结果:
复制代码
# 切换数据库
use db1;
# 查看是否存在t_student表
show tables;
# 查看t_student表中是否存在数据
select * from t_student;
存在数据即MySQL主从复制同步成功(主库操作,从库也会有)。
异常处理
复制代码
# 授权&创建用户
mysql> grant select,insert,file on test.* to test@'%' identified by '123';
ERROR 1221 (HY000): Incorrect usage of DB GRANT and GLOBAL PRIVILEGES
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select host,user from user;(test并没有权限)
+-----------+---------------+
| host | user |
+-----------+---------------+
| % | root |
| % | test |
| localhost | mysql.session |
| localhost | mysql.sys |
+-----------+---------------+
4 rows in set (0.00 sec)
mysql> show grants for test;
+----------------------------------+
| Grants for test@% |
+----------------------------------+
| GRANT USAGE ON *.* TO 'test'@'%' |【为默认权限,所有用户都有】
+----------------------------------+
1 row in set (0.00 sec)
mysql> grant select,insert on test.* to test@'%' identified by '123';