MySQL主从又叫做Replication、AB复制。简单讲就是A和B两台机器做主从后,在A上写数据,另外一台B也会跟着写数据,两者数据实时同步的
MySQL主从是基于binlog的,主上须开启binlog才能进行主从。
主从过程大致有3个步骤
1)主将更改操作记录到binlog里
2)从将主的binlog事件(sql语句)同步到从本机上并记录在relaylog里
3)从根据relaylog里面的sql语句按顺序执行
主上有一个log dump线程,用来和从的I/O线程传递binlog
从上有两个线程,其中I/O线程用来同步主的binlog并生成relaylog,另外一个SQL线程用来把relaylog里面的sql语句落地

MySQL主从介绍_第1张图片
准备工作
1、安装2台mysql
主mastr 192.168.1.3
从slave 192.168.1.4
修改my.cnf,增加server-id=3和log_bin=locala
[root@locala ~]# vim /etc/my.cnf

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html

[mysqld]

# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M

# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin

# These are commonly set, remove the # and set as required.
# basedir = .....
datadir =/data/mysql
# port = .....
server_id =3
socket = /tmp/mysql.sock
log_bin=locala
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

重启mysqld服务
创建用作同步数据的用户

mysql> grant replication slave on *.* to 'repl'@'192.168.1.4' identified by '123456';
Query OK, 0 rows affected (0.01 sec)   \\此处ip是客户的ip

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

mysql> show master status;
+---------------+----------+--------------+------------------+-------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set |
+---------------+----------+--------------+------------------+-------------------+
| master.000004 | 741 | | | |
+---------------+----------+--------------+------------------+-------------------+
1 row in set (0.00 sec)

mysql>

配置从
安装mysql
查看my.cnf,配置server-id=4,要求和主不一样
修改完配置文件后,启动或者重启mysqld服务
把主上test库同步到从上
可以先创建test库

主服务器上
binlog-do-db= //仅同步指定的库
binlog-ignore-db= //忽略指定库
从服务器上
replicate_do_db=
replicate_ignore_db=
replicate_do_table=
replicate_ignore_table=
replicate_wild_do_table= //如aming.%, 支持通配符%
replicate_wild_ignore_table=

主上 mysql -uroot aming
select count() from db;
truncate table db;
到从上 mysql -uroot aming
select count(
) from db;
主上继续drop table db;
从上查看db表