MySQL資料庫主從同步,mysql資料庫主從

來源:互聯網
上載者:User

MySQL資料庫主從同步,mysql資料庫主從

1,準備工作
準備兩台機器 ,各自安裝一個 MySQL資料庫 。比如

10.254.141.23 作為主要資料庫
10.254.166.60 作為從資料庫

安裝MySQL資料庫參考 《MySQL資料庫安裝》
2,主庫開啟binlog
看主庫上,是不是開啟了 binlog ,主從同步需要開啟這個。
mysql> show master status;

有binlog檔案 ,和 當前的位置顯示出來 ,說明開啟了binglog ,否則需要先去開這個, 修改/etc/my.cnf ,然後重啟資料庫。
設定檔中加這幾句
log-bin = mysql-bin
relay-log = relay-bin
binlog_format = MIXED
binlog_cache_size = 1M
3,主庫上建立同步帳號
在主機上 添加用於從庫同步的賬戶
mysql> GRANT REPLICATION SLAVE ON . to ‘repl’@’%’ identified by ‘123456’;
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

4,備份主庫的資料
如果主伺服器上 已經存在 資料, 需要先對 主庫的資料進行備份, 一次性匯入從庫上, 然後再主從同步 ,否則會出現資料衝突。
如果是全新安裝的 主從資料庫, 還沒有任何的資料寫入, 可以跳過這一步,直接去配置主從。

4.1
先對主庫資料進行備份
mysql> set sql_log_bin=0;
[root@rs1 ~]# /usr/local/bin/mysqldump -uroot -p123456 –socket=/home/mysql/mysql.sock –all-databases –single-transaction –flush-logs –master-data=2 > db.sql.2012-12-05
mysql> set sql_log_bin=1;

4.2
將備份資料複製到從伺服器上
[root@rs1 ~]# scp /home/work/db.sql.2012-12-05 10.136.51.111:/home/work

在從伺服器上進行資料同步:
mysql> source /home/work/db.sql.2012-12-05

5, 在從庫上 配置
head -30 db.sql.2012-12-05
找到以– CHANGE MASTER TO MASTER_LOG開頭的行,如下所示:
– CHANGE MASTER TO MASTER_LOG_FILE=’mysql-bin.000002’, MASTER_LOG_POS=107;
記錄使用的二進位檔案以及語句執行的位置。 因為要從這個位置開始 主從同步。

然後在從庫上執行
mysql> slave stop;
mysql>
change master to
master_host=’10.254.141.23’,
master_user=’repl’,
master_password=’123456’,
master_port=3306,
master_log_file=’mysql-bin.000007’,
master_log_pos=107;
mysql> slave start;

看一下 從庫的狀態。
mysql> show slave status\G;

         Slave_IO_Running: Yes        Slave_SQL_Running: Yes        Seconds_Behind_Master: 0   0顯示從伺服器比主伺服器慢多少秒

主從同步完成。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.