資料庫線上遷移的設想

壹頁書發表於2015-11-11
在分散式資料庫的環境下,應該經常有資料庫遷移的事情.

一個基於庫的資料庫線上遷移.
先做一個mysqldump到目標機,
因為這個過程很長,
完成之後,不斷追這段時間的binlog

然後,停止應用伺服器,應用最後一段binlog
最後手工檢查資料一致性.

這個只是相關的想法,指令碼未經過測試.不能用於生產環境.

  1. #/bin/bash
  2. source ~/.bashrc
  3. sourcehost='127.0.0.1'
  4. sourceport=3306
  5. sourceuser='root'
  6. sourcepwd='root'
  7. targethost='192.168.16.114'
  8. targetport=3306
  9. targetuser='xx'
  10. targetpwd='xx'
  11. binlogdir='/data'
  12. db='probe'

  13. #設定master_host
  14. mysql -u$targetuser -p$targetpwd -h$targethost -P$targetport -e "stop slave;reset slave all;change master to master_host='127.0.0.1';";

  15. #初次同步
  16. mysqldump -u$sourceuser -p$sourcepwd --master-data --single-transaction --databases $db | mysql -u$targetuser -p$targetpwd -h$targethost -P$targetport

  17. #獲取源資料庫的binlog資訊
  18. sourcebinloginfo=$(mysql -u$targetuser -p$targetpwd -h$targethost -P$targetport -Be "show slave status\G" | grep 'Master_Log_File\|Read_Master_Log_Pos' | grep -v Relay | awk '{print $2}')
  19. Master_Log_File=$(echo $sourcebinloginfo | awk -F " " '{print $1}')
  20. Read_Master_Log_Pos=$(echo $sourcebinloginfo | awk -F " " '{print $2}')

  21. echo "Master_Log_File:"$Master_Log_File
  22. echo "Read_Master_Log_Pos:"$Read_Master_Log_Pos

  1. function getSourceBinlog()
  2. {
  3.     binloginfo=$(mysql -u$sourceuser -p$sourcepwd -e "flush tables with read lock;show master status\Gunlock tables" | grep "File\|Position" | awk '{print $2}');
  4.     echo $binloginfo;
  5. }

  1. function applyBinlog()
  2. {
  3.     info=$(getSourceBinlog);
  4.     echo "info:"$info
  5.     endfile=$(echo $info | awk -F " " '{print $1}')
  6.     endpos=$(echo $info | awk -F " " '{print $2}')
  7.     while [ "$endfile" != "$startfile" ]
  8.     do
  9.         echo "Apply Binlog:"$startfile","$Read_Master_Log_Pos
  10.         mysqlbinlog $binlogdir"/"$startfile --database $db --start-position=$Read_Master_Log_Pos | mysql -u$targetuser -p$targetpwd -h$targethost -P$targetport
  11.         startfile=$(echo $startfile | awk -F "." '{printf("%s.%06d",$1,$2+1)}')
  12.         startpos=0
  13.     done
  14.     mysqlbinlog $binlogdir"/"$startfile --database $db --stop-position=$endpos | mysql -u$targetuser -p$targetpwd -h$targethost -P$targetport
  15.     startfile=$endfile
  16.     startpos=$endpos
  17. }
  18. startfile=$Master_Log_File
  19. startpos=$Read_Master_Log_Pos
  20. applyBinlog;
  21. applyBinlog;
  22. applyBinlog;
  23. applyBinlog;
  24. echo "確認停止中介軟體(Y/N)"
  25. read sure
  26. while [ "Y" != "$sure" ]
  27. do
  28.     echo "確認停止中介軟體(Y/N)"
  29.     read sure;
  30. done
  31. applyBinlog;


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1829484/,如需轉載,請註明出處,否則將追究法律責任。

相關文章