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語句落地html
準備工做
一、安裝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.cnfmysql
# 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服務
建立用做同步數據的用戶sql
mysql> <span class="crayon-e">grant </span><span class="crayon-e">replication </span><span class="crayon-e">slave </span><span class="crayon-e ">on *</span><span class="crayon-sy">.</span><span class="crayon-o">*</span> <span class="crayon-st">to</span> <span class="crayon-s">'repl'</span><span class="crayon-sy">@</span><span class="crayon-s">'192.168.1.4'</span> <span class="crayon-e">identified </span><span class="crayon-i">by</span> <span class="crayon-s">'123456'</span><span class="crayon-sy">;</span> 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庫vim
主服務器上
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表socket