MySQL主从介绍
MySQL主从叫做Replication、AB复制,A和B做主从后,在A上写数据。B上也会同步A的数据,两者实现实时同步 MySQL是基于binlog日志来同步的,主上必须开启binlog才能进行主从同步,同步过程大概有三个步骤 (1)主将数据操作更改的记录到binlog中 (2)主从之间同步比较binlog的事件记录,A将事件记录到binlog里,从同步到本地后也会在本机上记录一个relaylog的文件 (3)从根据relaylog里面的事件记录来执行同步 主上有一个log dump的线程,用来和从的I/O线程传递binlog 从上会有两个线程,其中I/O线程用于同步binlog的记录并产生relaylog记录,另一个SQL线程用来执行relaylog中的事务,把SQL数据在主上按大小、改变、来一一同步 主从同步有两种场景模式 主-从:主负责所有的数据查询和更改,从只负责数据的备份,只起到备份的作用 主写-从读:主负责数据来源的存储和修改,不用于数据查询。从不仅起到实时备份的作用,还对外部提供查询数据的访问,这样可以减小主数据库的访问压力
主从数据库准备
安装mysql数据库可以参考另一篇文章
对mysql的编译安装参数参考:
[root@localhost mysql-5.7.22]# cmake . -DCMALE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/var/mysql/data -DSYSCONFDIR=/etc -DWITH_MYISAM_STORAGE_ENGINE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_ARCHIVE_STORAGE_ENGINE=1 -DMYSQL_UNIX_ADDR=/usr/local/mysql/mysql.sock -DWITH_PARTITION_STORAGE_ENGINE=1 -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci -DWITH-SYSTEMD=1 -DWITH_BOOST=/usr/local/boost
-----------------------省略过程----------------------
-- CMAKE_C_LINK_FLAGS:
-- CMAKE_CXX_LINK_FLAGS:
-- CMAKE_C_FLAGS_RELWITHDEBINFO: -O3 -g -fabi-version=2 -fno-omit-frame-pointer -fno-strict-aliasing -DDBUG_OFF
-- CMAKE_CXX_FLAGS_RELWITHDEBINFO: -O3 -g -fabi-version=2 -fno-omit-frame-pointer -fno-strict-aliasing -DDBUG_OFF
-- Configuring done
-- Generating done
-- Build files have been written to: /usr/local/src/mysql-5.7.22
[root@localhost mysql-5.7.22]# echo $?
0
结果无报错,继续make编译
[root@localhost mysql-5.7.22]# make
Scanning dependencies of target abi_check
[ 0%] Built target abi_check
Scanning dependencies of target INFO_SRC
[ 0%] Built target INFO_SRC
Scanning dependencies of target INFO_BIN
[ 0%] Built target INFO_BIN
Scanning dependencies of target zlib
----------------省略过程------------------------
[ 99%] Building C object libmysqld/examples/CMakeFiles/mysql_client_test_embedded.dir/__/__/testclients/mysql_client_test.c.o
[ 99%] Linking CXX executable mysql_client_test_embedded
[ 99%] Built target mysql_client_test_embedded
Scanning dependencies of target my_safe_process
[100%] Building CXX object mysql-test/lib/My/SafeProcess/CMakeFiles/my_safe_process.dir/safe_process.cc.o
[100%] Linking CXX executable my_safe_process
[100%] Built target my_safe_process
[root@localhost mysql-5.7.22]# aecho $?
0
安装无报错,完成最后安装make install
-----------------------过程省略---------------------
-- Installing: /usr/local/mysql/support-files/mysqld_multi.server
-- Installing: /usr/local/mysql/support-files/mysql-log-rotate
-- Installing: /usr/local/mysql/support-files/magic
-- Installing: /usr/local/mysql/share/aclocal/mysql.m4
-- Installing: /usr/local/mysql/support-files/mysql.server
[root@localhost mysql-5.7.22]# echo $?
0
基本的安装完成,接下来就是配置mysql的启动和配置项 递归指定mysql所属用户和所属组的权限
[root@localhost ]# chown -R mysql:mysql /usr/local/mysql/
数据库的初始化 编译好的数据库进行初始化,其中mysql初始化信息中包含一个随机生成的密码
[root@localhost mysql-5.7.22]# /usr/local/mysql/bin/mysqld --initialize --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data
2018-07-28T09:08:42.088874Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2018-07-28T09:08:42.590615Z 0 [Warning] InnoDB: New log files created, LSN=45790
2018-07-28T09:08:42.861362Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2018-07-28T09:08:42.955937Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: d342a57c-9245-11e8-bf5e-080027a7f9c2.
2018-07-28T09:08:42.965634Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2018-07-28T09:08:42.966858Z 1 [Note] A temporary password is generated for root@localhost: tHuQg=%M!12j
my.cnf和/etc/init.d/mysqld文件 拷贝服务启动文件,并修改my.cnf配置文件。指定mysql安装路径和存储数据的路径及添加系统服务
[root@localhost ]# cp /usr/local/src/mysql-5.7.22/support-files/mysql.server /etc/init.d/mysqld
[root@localhost ]# vim /etc/init.d/mysqld
~
basedir=/usr/local/mysql/
datadir=/usr/local/mysql/data/
~
[root@localhost ]# chmod +x /etc/init.d/mysqld
[root@localhost ]# ls -l /etc/init.d/mysqld
-rwxr-xr-x 1 root root 10609 7月 28 17:21 /etc/init.d/mysqld
[root@localhost ]# chkconfig --add mysqld
[root@localhost ]# chkconfig --list
注意:该输出结果只显示 SysV 服务,并不包含原生 systemd 服务。SysV 配置数据可能被原生 systemd 配置覆盖。
如果您想列出 systemd 服务,请执行 'systemctl list-unit-files'。
欲查看对特定 target 启用的服务请执行
'systemctl list-dependencies [target]'。
mysqld 0:关 1:关 2:开 3:开 4:开 5:开 6:关
netconsole 0:关 1:关 2:关 3:关 4:关 5:关 6:关
network 0:关 1:关 2:开 3:开 4:开 5:开 6:关
编辑my.cnf的mysql配置文件,log-error是记录启动时报错的错误信息。在报错pid的错误中,有尝试把basedir = 的配置给注释掉,然后mysql能正常启动了,查看错误日志记录,日志记录报错unknown variable /usr/local/mysql/ 未知的变量路径,说明my.cnf指定的路径有问题,这里我直接注释掉basedir这个路径,然后启动成功
[root@localhost ]# less /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql/
datadir = /usr/local/mysql/data
port = 3306
character-set-server = utf8
explicit_defaults_for_timestamp = true
# socket = /var/run/mysqld/mysqld.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid
log-error = /data/mysql/logs/error.log
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
mysql的启动过程 添加完成跟随系统启动后,启动mysql服务:
[root@localhost ]# /etc/init.d/mysqld start
Starting MySQL.2018-07-28T09:23:23.822700Z mysqld_safe error: log-error set to '/var/log/mariadb/mariadb.log', however file don't exists. Create writable for user 'mysql'.
ERROR! The server quit without updating PID file (/usr/local/mysql/data/localhost.pid).
根据报错提示创建了mysql的日志文件,然后再尝试启动
[root@localhost ]# mkdir -p /var/log/mariadb/mariadb
[root@localhost ]# touch /var/log/mariadb/mariadb.log
[root@localhost ]# chown -R mysql:mysql /var/log/mariadb/mariadb
再次尝试启动mysql服务,并启动成功
[root@localhost support-files]# /etc/init.d/mysqld start
Starting MySQL. SUCCESS!
[root@localhost support-files]# ps -aux |grep mysql
root 21812 0.0 0.1 113312 1636 pts/0 S 17:28 0:00 /bin/sh /usr/local/mysql//bin/mysqld_safe --datadir=/usr/local/mysq/data --pid-file=/usr/local/mysql/data/localhost.pid
mysql 22000 1.7 16.3 1112372 166604 pts/0 Sl 17:28 0:00 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql/ --datadir=/usr/local/mysql/data --plugin-dir=/usr/local/mysql//lib/plugin --user=mysql --log-error=/var/log/mariadb/mariadb.log --pid-file=/usr/local/mysql/data/localhost.pid --port=3306
root 22030 0.0 0.0 112724 976 pts/0 R+ 17:28 0:00 grep --color=auto mysql
将mysql命令写入系统文件中,这样就能在命令行中直接使用mysql这个命令了
[root@localhost mysql]# echo "export PATH=$PATH:/usr/local/mysql/bin/" >>/etc/profile
[root@localhost mysql]# source /etc/profile
[root@localhost mysql]# echo "/usr/local/mysql/lib/" >>/etc/ld.so.conf
[root@localhost mysql]# ldconfig
建立master和slave的主从通信
步骤一
master主配置
清除iptables防火墙规则,由于没有清除iptables。导致进来的数据被转发重定向到其他IP地址上了
[root@aaa ~]# iptables -nvL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
4811 348K ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
1 84 ACCEPT icmp -- * * 0.0.0.0/0 0.0.0.0/0
4 324 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0
2 104 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 state NEW tcp dpt:22
13467 1028K REJECT all -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 REJECT all -- * * 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibited
Chain OUTPUT (policy ACCEPT 3311 packets, 1476K bytes)
pkts bytes target prot opt in out source destination
[root@aaa ~]# iptables -F
安装完mysql后,对my.cnf配置文件进行修改,添加binlog日志的记录,指定主从运行时的serverID。 修改my.cnf,添加binlog日志的产生配置并指定mysql的运行server级别ID 如果只同步或不同步的库,就需要在my.cnf中指定不同步或同步的库 #binlog-do-db=db1 #只针对指定库同步 #binlog-ignore-db=mysql 针对某些库不同步
[root@aaa /]# vim /etc/my.cnf
[mysqld]
basedir = /usr/local/mysql/
datadir = /usr/local/mysql/data
port = 3306
character-set-server = utf8
explicit_defaults_for_timestamp = true
server-id = 10
log-bin = zidingyi
在数据库中创建一个从数据库使用访问的授权用户,用于从在master中读取数据并进行同步的作用
mysql> grant replication slave on *.* to 'repl'@192.168.1.220 identified by 'xiangchen' ;
Query OK, 0 rows affected, 1 warning (0.00 sec)
查看主数据库中的binlog存储的值,这个是用于记录数据存储大小的记录的,如果数据表发生读写变化,这里也会发生改变。在主从同步前需要在主库锁表停止数据库读写。file是指定生成binlog文件的名称,Position是数据存储的变化值,通过这个值来进行同步,这个值也表达了binlog文件的改变大小
mysql> show master status;
+-----------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+-----------------+----------+--------------+------------------+-------------------+
| zidingyi.000001 | 1108 | | | |
+-----------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)
将主库锁表暂时禁止读取写入
mysql> flush tables with read lock;
Query OK, 0 rows affected (0.01 sec)
步骤二
slave从配置
slave角色上同样需要清除iptables规则,以免主从之间无法通信 slave从上配置my.cnf,修改server-id,这个id不能小于主上的配置,数值越小优先级越高。从服务器的my.cnf不需要配置log-bin,因为是slave的角色,所以只需要从master那里同步数据即可
[root@Huaching-2 ~]# vim /etc/my.cnf
[mysqld]
#bashdir = /usr/local/mysql/
datadir = /data/mysql
port = 3306
character-set-server = utf8
explicit_defaults_for_timestamp = true
server-id = 20
重启后登入从数据库中,先暂停slave的角色,并在数据库中写入与master通信的一些信息(binlog记录的数值)。 master_log_file是指定主上生成binlog文件的名称,slave会通过这个名称去找对应的binlog文件。 master_log_pos是指定master数据存储的变化值,通过这个值来进行同步,这个值也表达了binlog文件的改变大小
[root@Huaching-2 ~]# /etc/init.d/mysqld restart
Shutting down MySQL.. SUCCESS!
Starting MySQL.. SUCCESS!
mysql> stop slave ;
Query OK, 0 rows affected (0.01 sec)
mysql> change master to master_host='192.168.1.234', master_port=3306, master_user='slave', master_password='xiangchen', master_log_file='zidingyi.000001', master_log_pos=1108;
Query OK, 0 rows affected, 2 warnings (0.02 sec)
步骤三
解除master表锁和启动slave角色,进行数据同步
设置好master和slave的授权和访问账户设置后,解除master的表锁和启动slave的角色,并把master中的库拷贝到slave中,这样才能够保证启动同步时两边数据的一致性 在解除master的表锁之前,拷贝master数据到slave中,忽略明文密码的警告
[root@aaa ~]# mysqldump -uroot -ppwd@123 mysql2 > my2.db
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@aaa ~]# mysqldump -uroot -ppwd@123 zrlog > zrlog.db
mysqldump: [Warning] Using a password on the command line interface can be insecure.
将以db结尾的后缀备份文件通过scp、rzsz或者ftp等方法传输到slave上,slave在库中需要创建需要恢复库的一个空库,用于数据导入
mysql> create database mysql2;
Query OK, 0 rows affected (0.02 sec)
mysql> create database zrlog;
Query OK, 0 rows affected (0.02 sec)
mysql> exit
Bye
[root@Huaching-2 ~]# mysql -uroot -ppwd@123 mysql2 < my2.db
[root@Huaching-2 ~]# mysql -uroot -ppwd@123 zrlog < zrlog.db
master上可以把数据表锁解除掉,让主数据库可以正常读写访问
mysql> unlock tables;
mysql> flush privileges;
在从数据库启用slave的角色,并与master数据库进行数据同步(数据同步前两个数据库数据必须一致,否则同步会造成数据不一样的情况发生)
mysql> start slave;
Query OK, 0 rows affected (0.00 sec)
查看主从同步的信息,这里主要关注 Slave_IO_Running: Yes和 Slave_SQL_Running: Yes这两个值,一个表示是否和master正常通信的状态,Slave_IO是和master的IO进程通信的一个线程,yes表示在正常运行。另一个是表示SQL执行是否在监听状态
mysql> show slave status\G;
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 192.168.1.234
Master_User: slave
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: zidingyi.000001
Read_Master_Log_Pos: 1108
Relay_Log_File: Huaching-2-relay-bin.000002
Relay_Log_Pos: 319
Relay_Master_Log_File: zidingyi.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: 1108
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: 10
Master_UUID: 9174f3d7-9c9a-11e8-88a9-08002733edda
Master_Info_File: /data/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:
测试主从同步
master和slave的my.cnf中使用的同步配置
master的my.cnf中可以指定同步时排除或者只同步某些库 #binlog-do-db=db1 #只针对指定库同步 #binlog-ignore-db=mysql 针对某些库不同步
slave角色配置针对某些库完全记录执行,不会忽略掉binlog中某条SQL执行语句 replicate_wild_do_table= 支持通配符*,统配库,如user.* replicate_wild_ignore_table= 表示这个配置里的内容会被忽略执行
不建议使用以下的配置参数,因为匹配同步的库也有可能会被忽略不去执行 匹配库 replicate_do_db= replicate_ignore_db= 匹配表 replicate_do_table= replicate_ignore_table=
在主上查询库的操作,查询主从数据是否一致,相同的库、相同的表
mysql> use mysql2
Database changed
mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
| 6 |
+----------+
1 row in set (0.00 sec)
slave从上的查询结果
mysql> use mysql2
Database changed
mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
| 6 |
+----------+
1 row in set (0.00 sec)
在主上清空这个数据表的内容并查看数据表的行数
mysql> truncate table user;
Query OK, 0 rows affected (0.00 sec)
mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.00 sec)
slave从上只执行查询数据表行数的操作,结果是会把同样的数据执行同步过来
mysql> select count(*) from user;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.00 sec)
如果发生在从上删除表删除库的操作,此时master主上如果误执行了slave上被删除的内容的话,还会造成主从同步发生问题,只能通过重新在slave上指定position的值来进行同步了。这种误操作会破坏主从之间的同步
从删除某些内容后再次同步时发生的报错信息
Last_ SQL_ Error: Error 'Can't drop database 'user'; database doesn't exist' on query. Default database: 'user'. Query: 'drop database user'