Mysql主從複製原理
1.Mysql主從複製目的是爲了備份主庫數據,方便及時恢復數據,分擔主庫壓力。
2.Mysql主從複製屬於異步複製過程,整個過程需要開啓三個線程:Master側開啓I/O線程,Slave側開啓I/O、SQL線程。
3.Master側開啓bin-log二進制日誌功能,bin-log日誌主要用來記錄增、刪、改、更新操作的SQL語句。
4.Slave側通過I/O線程來讀取Master的bin-log文件內容,並把內容存儲在本地的中繼日誌relay-log中,同時會寫入master.info文件(該文件記錄master IP、端口、同步的用戶名、密碼、bin-log文件名以及最新的position位置點),供下次數據同步使用。
5.Slave側SQL線程檢測到中繼日誌內容有更新,解析更新的SQL語句,並在本地數據庫執行,保持Slave和Master數據同步的。
主從複製安裝配置
1.系統環境準備
Master:192.168.241.133
Slave:192.168.241.135
2.安裝
源碼安裝參考: http://blog.csdn.net/scott_bing/article/details/78261789 Yum安裝: yum install mysql-server mysql-devel mysql-libs -y CentOS6.x YUM安裝 yum install mariadb-server mariadb mariadb-libs -y CentOS7.x YUM安裝 |
3.Master側配置
在/etc/my.cnf中[mysqld]下添加以下代碼,配置完後重啓mysql服務
server-id = 1 log-bin = mysql-bin |
[client] port = 3306 socket = /tmp/mysql.sock [mysqld] port = 3306 socket = /tmp/mysql.sock skip-external-locking key_buffer_size =256M max_allowed_packet= 1M table_open_cache= 256 sort_buffer_size= 1M read_buffer_size= 1M read_rnd_buffer_size= 4M myisam_sort_buffer_size= 64M thread_cache_size= 8 query_cache_size=16M thread_concurrency= 8 log-bin=mysql-bin binlog_format=mixed server-id = 1 [mysqldump] quick max_allowed_packet= 16M [mysql] no-auto-rehash [myisamchk] key_buffer_size =128M sort_buffer_size= 128M read_buffer = 2M write_buffer = 2M [mysqlhotcopy] interactive-timeout |
創建供Slave庫進行同步的用戶、密碼,執行如下命令,最後查看主庫的狀態
grant replication slave on *.* to 'tongbu'@'%' identified by '123456'; flush privilege; 執行show master status 查看主庫的狀態 |
在/etc/my.cnf中[mysqld]段添加以下代碼:
server-id = 2 該值配置與master不一致即可 |
/etc/my.cnf完整配置:
[client] port = 3306 socket = /tmp/mysql.sock [mysqld] server-id = 2 port = 3306 socket = /tmp/mysql.sock skip-external-locking key_buffer_size =256M max_allowed_packet= 1M table_open_cache= 256 sort_buffer_size= 1M read_buffer_size= 1M read_rnd_buffer_size= 4M myisam_sort_buffer_size= 64M thread_cache_size= 8 query_cache_size=16M thread_concurrency= 8 [mysqldump] quick max_allowed_packet= 16M [mysql] no-auto-rehash [myisamchk] key_buffer_size =128M sort_buffer_size= 128M read_buffer = 2M write_buffer = 2M [mysqlhotcopy] interactive-timeout |
Slave指定Master IP、用戶名、密碼、bin-log文件名(mysql-bin.000010)及position(120),代碼如下:
change master to master_host='192.168.241.133',master_user='tongbu',master_password='123456',master_log_file='mysql-bin.000010',master_log_pos=120; |
start slave; show slave status; Slave_IO_Running: Yes Slave_SQL_Running: Yes |
Master側創建db_test數據庫和tb_01表,命令如下:
create database db_test charset=utf8; show databases; use db_test; create table tb_01(id varchar(20),name varchar(20)); show tables; |
Slave側查看是否有數據庫db_test和表tb_01,若有則表示Slave從Master複製數據成功