什么是主从同步(主从复制)
MySQL主从同步(MySQL Replication)是MySQL服务器的一个常用特性,它能够将MySQL服务器数据自动同步到其他MySQL服务器上,从而实现数据备份和负载均衡的功能。在实际应用中,MySQL主从同步可以用于实现高可用、灾备转移、读写分离等。
准备工作
1.至少准备好两台linux服务器
2.安装好mysql(mysql版本要一致,我用的5.7.43)
在mysql中查询版本是否一致
mysql> show variables like '%version%';
+-------------------------+------------------------------+
| Variable_name | Value |
+-------------------------+------------------------------+
| innodb_version | 5.7.43 |
| protocol_version | 10 |
| slave_type_conversions | |
| tls_version | TLSv1,TLSv1.1,TLSv1.2 |
| version | 5.7.43 |
| version_comment | MySQL Community Server (GPL) |
| version_compile_machine | x86_64 |
| version_compile_os | Linux |
+-------------------------+------------------------------+
8 rows in set (0.00 sec)
主服务器的配置
编写主服务器mysql的配置 /etc/my.cnf
#服务名称
[mysqld]
#数据库唯一ID,主从的标识号绝对不能重复。
server-id=1
#开启bin-log,并指定文件目录和文件名前缀
log-bin=mysql-bin
#需要同步哪一个数据库。如果是多个同步库,就以此格式另写几行即可。如果不指明对某个具体库同步,就去掉此行,表示同步所有库(除了ignore忽略的库)。
#binlog-do-db=test666
#不同步mysql系统数据库。如果是多个不同步库,就以此格式另写几行;也可以在一行,中间逗号隔开。
binlog-ignore-db=mysql
#确保binlog日志写入后与硬盘同步
sync_binlog=1
#数据存储路径
datadir=/var/lib/mysql
#指定套接字文件位置
socket=/var/lib/mysql/mysql.sock
#是否支持符号链接(0为不开启)
symbolic-links=0
#指定错误路径的存放路径
log-error=/var/log/mysqld.log
#为 mysqld 程序指定一个存放进程 ID 的文件
pid-file=/var/run/mysqld/mysqld.pid
#忽略大小写
lower_case_table_names=1
编写完成后一定要重启一下mysql服务让配置生效;
创建授权用户
#grant replication slave: 表示授予复制从服务器的权限。
#on *.*: 表示在所有数据库和所有表上执行授权操作。
#to slave@"192.168.100.%": 表示将权限授予用户名为"slave"的用户,该用户可以从IP地址以"192.168.100."开头的任何主机连接到MySQL服务器。
#identified by "Mysql@2023": 表示指定了用户的密码。在这种情况下,密码为"Mysql@2023"。
#由于密码策略的问题密码需要设置复杂一点,或者修改密码策略,修改后使用flush privileges;命令刷新一下
mysql> set global validate_password_policy=0;
mysql> set global validate_password_length=1;
#我这里依旧使用的复杂密码
mysql> grant replication slave on *.* to slave@"192.168.100.%" identified by "Mysql@2023";
Query OK, 0 rows affected, 1 warning (0.00 sec)
授权成功后,查看主从状态
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql-bin.000003 | 450 | | mysql | |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
查看二进制日志文件,这就是二进制文件存放的路径
[root@localhost ~]# find / -name mysql-bin*
/var/lib/mysql/mysql-bin.000001
查看 MySQL 二进制日志文件中的事件
show binlog events\G
从服务器的配置
编写从服务器mysql的配置 /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
server-id=2
symbolic-links=0
lower_case_table_names=1
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
修改好配置文件后,重启mysql服务
[root@localhost ~]# systemctl restart mysqld
在主服务器中查看mysql的主库状态
mysql> show master status\G
*************************** 1. row ***************************
File: mysql-bin.000003
Position: 900
Binlog_Do_DB:
Binlog_Ignore_DB: mysql
Executed_Gtid_Set:
1 row in set (0.00 sec)
登录从服务器的mysql,并实行同步命令()
mysql> change master to master_host='192.168.100.151',master_user='slave',master_password='Mysql@2023',master_log_file='mysql-bin.000003',master_log_pos=900;
Query OK, 0 rows affected, 2 warnings (0.00 sec)
注意:
master_host指从服务器的ip地址
master_user指主库授权给从库的账号也就是slave
master_password指密码
master_log_file 就是刚刚查询主库时,file文件的路径
master_log_pos就是position的值
配置完成后查看从库状态
mysql> show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.100.151
Master_User: slave
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000003
Read_Master_Log_Pos: 900
Relay_Log_File: localhost-relay-bin.000002
Relay_Log_Pos: 320
Relay_Master_Log_File: mysql-bin.000003
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB:
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 900
Relay_Log_Space: 531
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
Master_SSL_CA_Path:
Master_SSL_Cert:
Master_SSL_Cipher:
Master_SSL_Key:
Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
Last_IO_Errno: 0
Last_IO_Error:
Last_SQL_Errno: 0
Last_SQL_Error:
Replicate_Ignore_Server_Ids:
Master_Server_Id: 1
Master_UUID: 96ff636a-4b0e-11ee-aa71-000c29fd5cdc
Master_Info_File: /var/lib/mysql/master.info
SQL_Delay: 0
SQL_Remaining_Delay: NULL
Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
Master_Retry_Count: 86400
Master_Bind:
Last_IO_Error_Timestamp:
Last_SQL_Error_Timestamp:
Master_SSL_Crl:
Master_SSL_Crlpath:
Retrieved_Gtid_Set:
Executed_Gtid_Set:
Auto_Position: 0
Replicate_Rewrite_DB:
Channel_Name:
Master_TLS_Version:
1 row in set (0.00 sec)
如果正常的话,下面两个的值是yes状态,不正常就说明有问题
最后测试一下
登陆mysql数据库,并创建数据库以及测试的表,数据库名称为test666,表名为table666;
#登陆mysql
[root@localhost ~]# mysql -uroot -pMysql2023
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
[root@localhost ~]# mysql -uroot -pMysql@2023
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.43-log MySQL Community Server (GPL)
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#创建一个名为test666的数据库
mysql> create database test666;
Query OK, 1 row affected (0.00 sec)
#使用这个名为test66的库
mysql> use test666;
Database changed
#在这个库中创建一个名为table666的表,后面则是字段
mysql> CREATE TABLE table666(bTypeId int,bName char(16),price int,publishing char(16));
Query OK, 0 rows affected (0.01 sec)
mysql> INSERT INTO table666(bTypeId,bName,price,publishing) VALUES('1','Linux','66','DZ');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO table666(bTypeId,bName,price,publishing) VALUES('2','CLD','68','RM');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO table666(bTypeId,bName,price,publishing) VALUES('3','SYS','90','JX');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO table666(bTypeId,bName,price,publishing) VALUES('4','MySQL1','71','QH');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO table666(bTypeId,bName,price,publishing) VALUES('5','MySQL2','72','QH');
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO table666(bTypeId,bName,price,publishing) VALUES('6','MySQL3','73','QH');
Query OK, 1 row affected (0.00 sec)
mysql> select * from table666;
+---------+--------+-------+------------+
| bTypeId | bName | price | publishing |
+---------+--------+-------+------------+
| 1 | Linux | 66 | DZ |
| 2 | CLD | 68 | RM |
| 3 | SYS | 90 | JX |
| 4 | MySQL1 | 71 | QH |
| 5 | MySQL2 | 72 | QH |
| 6 | MySQL3 | 73 | QH |
+---------+--------+-------+------------+
6 rows in set (0.00 sec)
备份需要同步的数据,导出数据库并传给从服务器
#执行备份,将test666数据库备份到当前目录下,名称为test.sql
[root@localhost ~]# mysqldump -uroot -pMysql@2023 -B test666 > test.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@localhost ~]# ls
anaconda-ks.cfg test.sql
#scp命令将数据传给从服务器
[root@localhost ~]# scp test.sql 192.168.100.150:/root
The authenticity of host '192.168.100.150 (192.168.100.150)' can't be established.
ECDSA key fingerprint is SHA256:AzgJOeT5BDkY6L7Py/lEvvK+9kEEqPBrx9XvWMglHZk.
ECDSA key fingerprint is MD5:55:f1:99:15:47:2b:6b:af:5e:5c:95:bb:28:c8:47:00.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.100.150' (ECDSA) to the list of known hosts.
#输入服务器root账号的密码
root@192.168.100.150's password:
test.sql 100% 2336 2.2MB/s 00:00
接下来可以在从服务器的根目录下看到此文件
[root@localhost ~]# ls
anaconda-ks.cfg testdb.sql
从服务器导入备份文件
[root@localhost ~]# mysql -uroot -pMysql@2023 < test.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
从服务器登陆mysql查看数据
[root@localhost ~]# mysql -uroot -pMysql@2023
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 5.7.43 MySQL Community Server (GPL)
Copyright (c) 2000, 2023, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| test666 |
+--------------------+
5 rows in set (0.01 sec)
mysql> use test666;
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> show tables;
+-------------------+
| Tables_in_test666 |
+-------------------+
| table666 |
+-------------------+
1 row in set (0.00 sec)
mysql> select * from table666;
+---------+--------+-------+------------+
| bTypeId | bName | price | publishing |
+---------+--------+-------+------------+
| 1 | Linux | 66 | DZ |
| 2 | CLD | 68 | RM |
| 3 | SYS | 90 | JX |
| 4 | MySQL1 | 71 | QH |
| 5 | MySQL2 | 72 | QH |
| 6 | MySQL3 | 73 | QH |
+---------+--------+-------+------------+
6 rows in set (0.00 sec)
到主库的表中去添加内容
mysql> INSERT INTO table666(bTypeId,bName,price,publishing) VALUES('7','MySQL3','74','QH');
Query OK, 1 row affected (0.00 sec)
上从库查询一下内容是否有更新
mysql> select * from table666;
+---------+--------+-------+------------+
| bTypeId | bName | price | publishing |
+---------+--------+-------+------------+
| 1 | Linux | 66 | DZ |
| 2 | CLD | 68 | RM |
| 3 | SYS | 90 | JX |
| 4 | MySQL1 | 71 | QH |
| 5 | MySQL2 | 72 | QH |
| 6 | MySQL3 | 73 | QH |
| 7 | MySQL3 | 74 | QH |
+---------+--------+-------+------------+
7 rows in set (0.00 sec)
从这里可以看出从库中的内容也更新了。
到这里主从同步(复制)就完成了。