MySql教程

mysql主从

本文主要是介绍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主从的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!