mysql主从

1. 主从简介

在现代企业中,数据显得尤为重要,而存储数据的数据库选择又五花八门,但无论是何种数据库,均存在着一种隐患。

想几个问题:

  • 用一台数据库存放数据,若此数据库服务器宕机了导致数据丢失怎么办?
  • 业务量大了,数据多了,访问的人多了,一台数据库无法保证服务质量了怎么办?

1.1 主从作用

  • 实时灾备,用于故障切换
  • 读写分离,提供查询服务
  • 备份,避免影响业务(备份的实例,服务器)

1.2 主从形式

  • 一主一从:主出问题,从顶上。
  • 主主复制:其中一个主工作,另外一个不会工作,两个的数据都会挂载到某一个共享存储上。
  • 一主多从---扩展系统读取的性能,因为读是在从库读取的:一个主负责写,多个从负责读。一般用于写少读多。
  • 多主一从---5.7开始支持:这一个从里面包括了多个主的数据。一般用于写多读少。
  • 联级复制

2. 主从复制原理


主从复制步骤:

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

3. 主从复制配置

主从复制配置步骤:

  1. 确保从数据库与主数据库里的数据一样
  2. 在主数据库里创建一个同步账号授权给从数据库使用
  3. 配置主数据库修改配置文件
  4. 配置从数据库修改配置文件

需求:
搭建两台MysqL服务器,一台作为主服务器,一台作为从服务器,主服务器进行写操作,从服务器进行读操作

环境说明:

数据库角色IP应用与系统版本有无数据
数据库 172.16.12.128 centos8/redhat8
MysqL-5.7
有数据
数据库 172.16.12.129 centos8/redhat8
MysqL-5.7
无数据

3.1 MysqL安装

分别在主从两台服务器上安装MysqL-5.7版本,此处略过安装步骤,若有疑问请参考《MysqL基础》与《MysqL进阶》两篇文章

3.2 MysqL主从配置

3.2.1 确保从数据库与主数据库里的数据一样

为确保从数据库与主数据库里的数据一样,先全备主数据库并还原到从数据库

//先查看主库有哪些库
[root@localhost ~]# MysqL -uroot -pwangqing123! -e 'show databases;'
MysqL: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| MysqL              |
| performance_schema |
| student            |
| sys                |
| teacher            |
+--------------------+

//再查看从库有哪些库
[root@localhost ~]# MysqL -uroot -pwangqing123! -e 'show databases;'
MysqL: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| MysqL              |
| performance_schema |
| sys                |
+--------------------+


//全备主库
//全备主库时需要另开一个终端,给数据库加上读锁,避免在备份期间有其他人在写入导致数据不一致
MysqL> FLUSH TABLES WITH READ LOCK;
Query OK, 0 rows affected (0.00 sec)
//此锁表的终端必须在备份完成以后才能退出

//备份主库并将备份文件传送到从库
[root@localhost ~]# MysqLdump -uroot -pwangqing123! --all-databases > /opt/all-201808191200.sql
MysqLdump: [Warning] Using a password on the command line interface can be insecure.
[root@localhost ~]# ls /opt/
all-201808191200.sql
[root@localhost ~]# scp /opt/all-201808191200.sql root@172.16.12.129:/opt/
root@172.16.12.129's password:
all-201808191200.sql                              100%  786KB  10.6MB/s   00:00 

//解除主库的锁表状态,直接退出交互式界面即可
MysqL> quit
Bye


//在从库上恢复主库的备份并查看从库有哪些库,确保与主库一致
[root@localhost ~]# MysqL -uroot -pwangqing123! < /opt/all-201808191200.sql
MysqL: [Warning] Using a password on the command line interface can be insecure.
[root@localhost ~]# MysqL -uroot -pwangqing123! -e 'show databases;'
MysqL: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| MysqL              |
| performance_schema |
| student            |
| sys                |
| teacher            |
+--------------------+

3.2.2 在主数据库里创建一个同步账号授权给从数据库使用

MysqL> grant replication slave on *.* to 'repl'@'192.168.6.134' identified by 'repl123!';  # 创建一个repl数据库用户,密码是repl123!赋予权限
MysqL> flush privileges;  # 刷新授权表
Query OK, 0 rows affected (0.00 sec)

3.2.3 配置主数据库

[MysqLd]
basedir = /usr/local/MysqL
datadir = /opt/data
socket = /tmp/MysqL.sock
port = 3306
pid-file = /opt/data/MysqL.pid
user = MysqL
skip-name-resolve
sql-mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

server-id=10    #启用binlog日志
log-bin=MysqL_bin  #数据库服务器唯一标识符,主库的server-id值必须比从库的小
 # 重启MysqL服务
[root@localhost ~]# systemctl restart MysqLd   # 重启
[root@localhost ~]# systemctl status MysqLd    #查看状态
● MysqLd.service - MysqL server daemon
   Loaded: loaded (/usr/lib/systemd/system/MysqLd.service; enabled; >
   Active: active (running) since Mon 2022-07-04 04:09:23 CST; 22s a>
  Process: 1857 ExecStop=/usr/local/MysqL/support-files/MysqLd stop >
  Process: 1889 ExecStart=/usr/local/MysqL/support-files/MysqLd star>
 Main PID: 1902 (MysqLd_safe)
    Tasks: 28 (limit: 23485)
   Memory: 183.0M
   CGroup: /system.slice/MysqLd.service
           ├─1902 /bin/sh /usr/local/MysqL/bin/MysqLd_safe --datadir>
           └─2130 /usr/local/MysqL/bin/MysqLd --basedir=/usr/local/m>

7月 04 04:09:22 localhost.localdomain systemd[1]: Starting MysqL ser>
7月 04 04:09:23 localhost.localdomain MysqLd[1889]: Starting MysqL. >
7月 04 04:09:23 localhost.localdomain systemd[1]: Started MysqL serv>
lines 1-15/15 (END)
//查看主库的状态
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)

3.2.4 配置从数据库

[root@localhost ~]# vi /etc/my.cnf

[MysqLd]
basedir = /usr/local/MysqL
datadir = /opt/data
socket = /tmp/MysqL.sock
port = 3306
pid-file = /opt/data/MysqL.pid
user = MysqL
skip-name-resolve
sql-mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

server-id = 20     # 从库的server-id值必须大于主库的该值
relay-log = myrelay  # 启用中继日志relay-log
#重启从库的MysqL服务
[root@localhost ~]# systemctl restart MysqLd
[root@localhost ~]# systemctl status MysqLd
● MysqLd.service - MysqL server daemon
   Loaded: loaded (/usr/lib/systemd/system/MysqLd.service; enabled; >
   Active: active (running) since Sun 2022-07-03 20:22:00 CST; 3s ago
  Process: 1842 ExecStop=/usr/local/MysqL/support-files/MysqLd stop >
  Process: 1874 ExecStart=/usr/local/MysqL/support-files/MysqLd star>
 Main PID: 1889 (MysqLd_safe)
    Tasks: 28 (limit: 23485)
   Memory: 180.4M
   CGroup: /system.slice/MysqLd.service
           ├─1889 /bin/sh /usr/local/MysqL/bin/MysqLd_safe --datadir>
           └─2115 /usr/local/MysqL/bin/MysqLd --basedir=/usr/local/m>

7月 03 20:21:59 localhost.localdomain systemd[1]: Starting MysqL ser>
7月 03 20:22:00 localhost.localdomain MysqLd[1874]: Starting MysqL. >
7月 03 20:22:00 localhost.localdomain systemd[1]: Started MysqL serv>
lines 1-15/15 (END)
#配置并启动主从复制,从库配置

MysqL> change master to       # 主是
    -> master_host='192.168.6.133',  # 主的ip
    -> master_user='repl',    # 主的用户名字
    -> master_password='repl123!',   # 用户的密码
    -> master_log_file='MysqL_bin.000001',   #放数据的二进制文件名字
    -> master_log_pos=154;      # 记录的位子
 Query OK, 0 rows affected, 2 warnings (0.00 sec)

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.6.133
                  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   # 要IO进程和sql进程都是yes
            Slave_sql_Running: Yes

验证

 

# 主数据库里操作
MysqL>  show databases;   #创建一个school库
+--------------------+
| Database           |
+--------------------+
| information_schema |
| MysqL              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

MysqL> create database school;
Query OK, 1 row affected (0.01 sec)

MysqL> show databases;   # 查看
+--------------------+
| Database           |
+--------------------+
| information_schema |
| MysqL              |
| performance_schema |
| school             |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

从库查看

MysqL> show databases;   # 有school库
+--------------------+
| Database           |
+--------------------+
| information_schema |
| MysqL              |
| performance_schema |
| school             |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

主库操作

MysqL> create table sym(id int primary key auto_increment,name varchar   #  创建sym表
Query OK, 0 rows affected (0.01 sec)

MysqL> show tables;
+------------------+
| Tables_in_school |
+------------------+
| sym              |
+------------------+
1 row in set (0.00 sec)

从库

MysqL> use school;
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_school |
+------------------+
| sym              |
+------------------+
1 row in set (0.00 sec)   # 主库创建的从库也可以查看到

主库操作

MysqL> insert into sym (id,name) values(1,'zhangsan'),(2,'lisi'),(3,'wangwu'),(4,'zhaoliu');   #往表里添加数据
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

MysqL> select * from sym;  # 查看
+----+----------+
| id | name     |
+----+----------+
|  1 | zhangsan |
|  2 | lisi     |
|  3 | wangwu   |
|  4 | zhaoliu  |
+----+----------+
4 rows in set (0.00 sec)

从库查看

MysqL> select * from sym;
+----+----------+
| id | name     |
+----+----------+
|  1 | zhangsan |
|  2 | lisi     |
|  3 | wangwu   |
|  4 | zhaoliu  |
+----+----------+
4 rows in set (0.00 sec)  #从库查看

 

相关文章

MySQL 死锁 是指两个或多个事务互相等待对方持有的锁,从而导...
在MySQL中,InnoDB引擎通过Next-Key Locking技术来解决幻读问...
在数据库事务管理中,Undo Log 和 Redo Log 是两种关键日志,...
case when概述 sql语句中的case语句与高级语言中的switch语句...
其实很简单,只是为了忘记,做个记录,用的时候方便。 不管是...
1.进入服务,找到mysql服务,在属性里找到mysql的安装路径 2...