天天看點

使用KeepAlived搭建MySQL高可用環境

<a href="http://s5.51cto.com/wyfs02/M01/85/80/wKioL1el5dCjv2UdAAAtiTGNXZg341.png" target="_blank"></a>

使用KeepAlived搭建MySQL的高可用環境。

首先搭建MySQL的主從複制

在Master開啟binlog,建立複制帳号,

然後在Slave輸入指令

change master to

master_host='192.168.1.70',

master_port=3306,

master_user='xx',

master_password='xx';

然後使用start slave開啟複制。

然後編譯安裝KeepAlived

進入keepalived-1.2.12目錄

然後使用

./configure

make &amp;&amp; make install

然後在Master伺服器編輯KeepAlived的配置檔案

vim /etc/keepalived/keepalived.conf

! Configuration File for keepalived

global_defs {

    router_id HA_MySQL

}

vrrp_instance VI_1 {

     state BACKUP

     interface eth0

     virtual_router_id 51

     priority 100

     advert_int 1

     nopreempt

     authentication {

         auth_type PASS

         auth_pass 1111

     }

     virtual_ipaddress {

         192.168.1.199

virtual_server 192.168.1.199 3306 {

     delay_loop 2

     lb_algo wrr

     lb_kind DR

     persistence_timeout 60

     protocol TCP

     real_server 192.168.1.70 3306 {

         weight 3

         notify_down /root/shutdown.sh

         TCP_CHECK {

             connect_timeout 10

             nb_get_retry 3

             delay_before_retry 3

             connect_port 3306

         } 

然後編輯Slave的配置檔案

     router_id HA_MySQL

     priority 90

         192.168.1.199

     real_server 192.168.1.80 3306 {

         }

其中

priority                      表示優先級

virtual_ipaddress      虛拟的IP位址(VIP)

delay_loop                每個2秒檢查一次real_server狀态

notify_down              檢測到服務down後執行的腳本 

connect_timeout      連接配接逾時時間

nb_get_retry             重連次數

delay_before_retry   重連間隔時間

connect_port            健康檢查端口

shutdown.sh 可以考慮加入郵件告警的功能。

#!/bin/bash

pkill keepalived

在兩個伺服器上啟動MySQL和KeepAlived服務

service mysql start

service keepalived start

Master的server_id為1

Slave的server_id為2

然後 連接配接VIP的MySQL,可以看到已經連接配接到了Master伺服器(server_id為1)

<a href="http://s1.51cto.com/wyfs02/M00/85/80/wKioL1el5gHgJyMgAACA0jTIFF4436.png" target="_blank"></a>

如果kill掉Master的MySQL,KeepAlived會自動轉移到Slave

在Master伺服器上執行

killall mysqld

然後再次檢視server_id,

短暫的失去連接配接之後,再次連接配接上VIP,server_id已經變為2,說明VIP已經指向了Slave

<a href="http://s2.51cto.com/wyfs02/M00/85/80/wKioL1el5iWwNkh-AABSMUQ5OCY638.png" target="_blank"></a>

nopreempt參數表示Master恢複正常之後,是否将VIP繼續指向Master

這樣的話,會再次引發切換。

兩台伺服器的KeepAlived會有心跳檢測,

如果Master的MySQL服務挂了(3306端口挂了),那麼他會選擇自殺.

Slave的KeepAlived通過心跳檢測發現這個情況,就會将VIP的請求接管。

KeepAlived還有很多參數沒有明白是什麼意思

生産環境的切換腳本,在Slave提升為Master之後,應該等待所有的中繼日志應用完畢,否則可能丢失資料

      本文轉自灬落魄灬  51CTO部落格,原文連結:http://blog.51cto.com/smoke520/1830071,如需轉載請自行聯系原作者

繼續閱讀