mysql 主从

本文详细介绍了MySQL的主从复制配置过程,包括一主一从、主主复制等模式,以及如何进行全备主库、配置主从复制、启动复制,并通过实例验证了数据同步的正确性。重点涉及了binlog、relaylog、权限配置、主从状态检查等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主从作用
  • 实时灾备,用于故障切换
  • 读写分离,提供查询服务
  • 备份,避免影响业务

主从形式

在这里插入图片描述

  • 一主一从
  • 主主复制
  • 一主多从—扩展系统读取的性能,因为读是在从库读取的
  • 多主一从—5.7开始支持
  • 联级复制

主从复制步骤:
在这里插入图片描述

主库将所有的写操作记录到binlog日志中并生成一个log dump线程,将binlog日志传给从库的I/O线程
从库生成两个线程,一个I/O线程,一个SQL线程
I/O线程去请求主库的binlog,并将得到的binlog日志写到relay log(中继日志) 文件中
SQL线程,会读取relay log文件中的日志,并解析成具体操作,来实现主从的操作一致,达到最终数据一致的目的

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> create database yt;
Query OK, 1 row affected (0.00 sec)

mysql> use yt;
Database changed
mysql> create table student(id int not null primary key auto_increment ,name varchar(50),age tinyint);
Query OK, 0 rows affected (0.01 sec)

mysql> insert student(name,age) values('tom',20),('jerry',25);
Query OK, 2 rows affected (0.20 sec)
Records: 2  Duplicates: 0  Warnings: 0

//全备主库
//全备主库时需要另开一个终端,给数据库加上读锁,避免在备份期间有其他人在写入导致数据不一致

mysql> flush tables with read lock;
Query OK, 0 rows affected (0.00 sec)

//此锁表的终端必须在备份完成以后才能退出


mysql> use yt;
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 * from student;
+----+-------+------+
| id | name  | age  |
+----+-------+------+
|  1 | tom   |   20 |
|  2 | jerry |   25 |
+----+-------+------+
2 rows in set (0.00 sec)

//备份主库并将备份文件传送到从库
[root@localhost ~]# mysqldump -uroot -p123 --all-databases > all.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@localhost ~]# ls
all.sql  anaconda-ks.cfg  mysql
[root@localhost ~]# 

[root@localhost ~]# scp all.sql 192.168.11.149:~
root@192.168.11.149's password: 
all.sql         100%  841KB  16.5MB/s   00:00 
[root@localhost ~]# ls
anaconda-ks.cfg  mysql
[root@localhost ~]# ls
all.sql  anaconda-ks.cfg  mysql
在主数据库里创建一个同步账号授权给从数据库使用
mysql> grant replication slave on *.* to repl@192.168.11.149 identified by 'repl123';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> 

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> 



[root@slave ~]# mysql -urepl  -p'repl123' -h192.168.11.151
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 11
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

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> 


配置主数据库
[root@master ~]# vim /etc/my.cnf 

[mysqld]
basedir = /usr/local/mysql
datadir = /data/3306
socket = /tmp/mysql.sock
port = 3306
pid-file = /data/3306/mysql.pid
user = mysql
skip-name-resolve


log-bin=mysql-bin   //启用binlog日志
server-id=1     //数据库服务器唯一标识符,主库的server-id值必须比从库的小
[root@master ~]# service  mysqld restart
Shutting down MySQL.... SUCCESS! 
Starting MySQL. SUCCESS! 

//查看主库的状态
mysql> show master status;
+------------------+----------+--------------+------------------+-------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+------------------+----------+--------------+------------------+-------------------+
| mysql_bin.000001 |      154 |              |                  |                   |
+------------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec

//配置并启动主从复制
[root@slave ~]# vim /etc/my.cnf 

[mysqld]
basedir = /usr/local/mysql
datadir = /data/3306
socket = /tmp/mysql.sock
port = 3306
pid-file = /data/3306/mysql.pid
user = mysql
skip-name-resolve

server-id=20    //设置从库的唯一标识符,从库的server-id值必须大于主库的该值       //启用中继日志relay-log
relay-log=mysql

//重启从库的mysql服务
[root@slave ~]# service mysqld restart
Shutting down MySQL.. SUCCESS! 
Starting MySQL. SUCCESS! 
[root@slave ~]# 
[root@slave ~]# ss -antl
State  Recv-Q  Send-Q   Local Address:Port   Peer Address:Port 
LISTEN 0       128            0.0.0.0:22          0.0.0.0:*    
LISTEN 0       128               [::]:22             [::]:*    
LISTEN 0       80                   *:3306              *:*    


//配置并启动主从复制
mysql> change master to master_host='192.168.11.151',master_user='repl',master_password='repl123',master_log_file='mysql_bin.000002',master_log_pos=154;
Query OK, 0 rows affected, 2 warnings (0.31 sec)

mysql> 

mysql> start slave;
Query OK, 0 rows affected (0.00 sec)


//查看从服务器状态
mysql> change master to master_host='192.168.11.151',master_user='repl',master_password='repl123',master_log_file='mysql_bin.000001',master_log_pos=1544;
Query OK, 0 rows affected, 2 warnings (0.00 sec)

mysql> show master status;
Empty set (0.00 sec)

mysql> start stave;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'stave' at line 1
mysql> start slave;
Query OK, 0 rows affected (0.00 sec)

mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.11.151
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql_bin.000001
          Read_Master_Log_Pos: 154
               Relay_Log_File: myrelay.000002
                Relay_Log_Pos: 320
        Relay_Master_Log_File: mysql_bin.000001
             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: 154
              Relay_Log_Space: 519
              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: 10
                  Master_UUID: 8ca08f25-19ea-11eb-9797-000c294a1cab
             Master_Info_File: /data/3306/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)

mysql> 



测试验证
在主服务器的创建shool数据库

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> create database shool;
Query OK, 1 row affected (0.00 sec)
`

在从数据库中查看数据是否同步

mysql> create database shool;
Query OK, 1 row affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| shool              |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值