MySQL之Haproxy+Keepalived+MySQL高可用均衡負載部署 (網絡摘抄)

來源於:https://blog.csdn.net/weisong530624687/article/details/71536837?utm_source=blogxgwz3html

1、安裝主從MySQLmysql

1. 按照Linux-rpm安裝MySQL步驟完成MySQL安裝;linux

2. 修改啓動的配置文件c++

(1)複製/usr/share/mysql路徑下的my-default.cnf文件或my-medium.cnf文件至/etc目錄redis

(2)修改配置文件:sql

server-id = 91   #指定服務器ID數據庫

thread_concurrency = 4 #bootstrap

log-bin = mysql-bin    #開啓二進制日誌vim

skip-name-resolve緩存

binlog-ignore = mysql   #忽略mysql和information_schema

binlog-ignore = information_schema

binlog-do_db = integrator_db #同步的數據庫名,不配置此項則默認同步全部數據庫

 

(3)在Master服務器上建立MySQL用戶(受權複製用戶)

命令:grant replication slave on *.* to '用戶名'@'slave IP地址' identified by '密碼';

(4)查看master狀態

命令:show master status;

 

 

(5)同步驟(2)修改slave的配置文件,其中server-id要設置比master大

 

(6)在slave添加master配置

命令:change master to

->master_host='master主機IP',

->master_port='master mysql服務使用端口',

->master_user='master mysql遠程用戶名',

->master_password='master mysql遠程密碼',

->master_log_file='master二進制日誌文件',    #show master status中File的值

->master_log_pos='master日誌地址';         show master status中Position的值

 

(7)主從同步測試

命令:show slave status\G

當Slave_IO_Running和Slave_SQL_Running均爲Yes時,表示同步成功。

 

 

2、安裝Haproxy

 

 master和slave安裝配置步驟相同。

 

一、上傳安裝包、受權並解壓;

命令:chmod 755 安裝包名稱;

tar -zxvf 安裝包名稱;

如本次使用haproxy-1.4.8.tar.gz安裝包。  

 

二、編譯、安裝

(1)查看系統內核,選擇對應編譯命令

查看內核命令:uname -a

(2)編譯

若是是32位系統,則命令爲:make TARGET=linux26 ARCH=i386 PREFIX=編譯路徑

若是是64位系統,則命令爲:make TARGET=linux26 ARCH=x86_64PREFIX=編譯路徑

假設本次系統爲64位,安裝路徑爲/var/local/haproxy,則命令爲:make TARGET=linux26 ARCH=x86_64 PREFIX=/var/local/haproxy

(3)安裝

命令:make install PREFIX=編譯路徑

同步驟(2),命令爲:make install PREFIX=/var/local/haproxy

 

三、建立配置文件、日誌目錄

命令:mkdir -p /var/local/haproxy/logs/var/local/haproxy/conf  /var/local/haproxy/sbin

四、編輯配置文件

命令:vim /var/local/haproxy/conf/haproxy.conf,配置文件內容:

global    

    log         127.0.0.1 local2  

    chroot      /var/lib/haproxy    

    pidfile     /var/run/haproxy.pid   

    maxconn     4096   

    user        haproxy    

    group       haproxy    

    daemon

    # turn on stats unix socket

    stats socket /var/lib/haproxy/stats

defaults     

    mode                    http    

    log                     global   

    option                  tcplog

    option                  dontlognull   

    option                  redispatch   

    retries                 3    

    timeout queue           1m

    timeout connect         10s   

    timeout client          1m    

    timeout server          1m    

    timeout check           10s

    maxconn                 4096

listen mysql_proxy

        bind 0.0.0.0:3307

        mode tcp

        balance  source

        option mysql-check user root password 111111    #遠程用戶

        server mysqldb1 192.168.0.91:3306 weight 1  check  inter 1s rise 2 fall 2        #master mysql

        server mysqldb2 192.168.0.121:3306 weight 2  check  inter 1s rise 2 fall 2 backup         #slave mysql

listen stats     #監控

       mode http

       bind 0.0.0.0:8888

       stats enable

       stats uri /dbs

       stats realm Global\ statistics

       stats auth admin:admin

配置文件說明同均衡負載-haproxy配置文件說明

 

五、haproxy啓動腳本管理

    命令:vi /etc/init.d/haproxy,增長配置:

#!/bin/bash

#

# chkconfig: 2345 85 15

# description: HA-Proxy is a TCP/HTTP reverse proxy which is particularly suited \

#              for high availability environments.

# processname: haproxy

# config: /etc/haproxy.cfg

# pidfile: /var/run/haproxy.pid

 

# Source function library.

if [ -f /etc/init.d/functions ]; then

  . /etc/init.d/functions

elif [ -f /etc/rc.d/init.d/functions ] ; then

  . /etc/rc.d/init.d/functions

else

  exit 0

fi

 

CONF_FILE="/etc/haproxy/haproxy.cfg"

HAPROXY_BINARY="/usr/local/sbin/haproxy"

PID_FILE="/var/run/haproxy.pid"

 

# Source networking configuration.

. /etc/sysconfig/network

 

# Check that networking is up.

[ ${NETWORKING} = "no" ] && exit 0

 

[ -f ${CONF_FILE} ] || exit 1

 

RETVAL=0

 

start() {

  $HAPROXY_BINARY -c -q -f $CONF_FILE

  if [ $? -ne 0 ]; then

    echo "Errors found in configuration file."

    return 1

  fi

 

  echo -n "Starting HAproxy: "

  daemon $HAPROXY_BINARY -D -f $CONF_FILE -p $PID_FILE

  RETVAL=$?

  echo

  [ $RETVAL -eq 0 ] && touch /var/lock/subsys/haproxy

  return $RETVAL

}

 

stop() {

  echo -n "Shutting down HAproxy: "

  killproc haproxy -USR1

  RETVAL=$?

  echo

  [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/haproxy

  [ $RETVAL -eq 0 ] && rm -f $PID_FILE

  return $RETVAL

}

 

restart() {

  $HAPROXY_BINARY -c -q -f $CONF_FILE

  if [ $? -ne 0 ]; then

    echo "Errors found in configuration file, check it with 'haproxy check'."

    return 1

  fi

  stop

  start

}

 

check() {

  $HAPROXY_BINARY -c -q -V -f $CONF_FILE

}

 

rhstatus() {

  pid=$(pidof haproxy)

  if [ -z "$pid" ]; then

    echo "HAProxy is stopped."

    exit 3

  fi

  status haproxy

}

 

condrestart() {

  [ -e /var/lock/subsys/haproxy ] && restart || :

}

 

# See how we were called.

case "$1" in

  start)

    start

    ;;

  stop)

    stop

    ;;

  restart)

    restart

    ;;

  reload)

    restart

    ;;

  condrestart)

    condrestart

    ;;

  status)

    rhstatus

    ;;

  check)

    check

    ;;

  *)

    echo $"Usage: haproxy {start|stop|restart|reload|condrestart|status|check}"

    RETVAL=1

esac

 

exit $RETVAL

     

 

 

6 、開啓系統日誌文件支持

(1)修改/etc/syslog.conf,命令:vim /etc/syslog.conf ,添加內容:

local2.*   /var/local/haproxy/logs/haproxy.log     #注意:local數字 該值與haproxy.conf中的配置保持一致

(2)修改/etc/sysconfig/syslog,命令:vim/etc/sysconfig/rsyslog,添加內容:

SYSLOGD_OPTIONS=」-c 2 -r -m 0″          #註釋:-c 2 使用兼容模式,默認是 -c 5,-r開啓遠程日誌,-m 0標記時間戳。單位是分鐘,爲0時,表示禁用該功能

(3)重啓rsyslog服務,命令:/etc/init.d/rsyslog restart

(4)重啓haproxy服務,命令:haproxy -f /var/haproxy/conf/haproxy.con

 

七、可打開網頁查看haproxy監控mysql的狀況

URL:http://haproxy服務器地址:端口/路徑

如步驟4配置的URL地址爲:http://192.168.0.121:8888/dbs,用戶名/密碼均爲admin

 

 

具體安裝步驟可參考:http://www.poluoluo.com/server/201601/450417.html

http://www.tuicool.com/articles/67ZFBr

 

3、Keepalived安裝配置

一、上傳安裝包、受權並解壓;

命令:chmod 755 安裝包名稱;

tar  -zxvf 安裝包名稱;

    如本次使用keepalived-1.2.12.tar.gz安裝包。

 

二、編譯、安裝

命令:./configure

make& make install

 

三、準備配置文件

命令: cp /usr/local/etc/rc.d/init.d/keepalived /etc/rc.d/init.d/

cp /usr/local/etc/sysconfig/keepalived /etc/sysconfig/

mkdir /etc/keepalived

cp /usr/local/etc/keepalived/keepalived.conf /etc/keepalived/

cp /usr/local/sbin/keepalived /usr/sbin/

四、修改配置文件

(1)master配置文件:

global_defs {
    notification_email {
        mona.lai@sinoservices.com   //receiver email
   }
   notification_email_fromkobe.lv@sinoservices.com   //sender email
   smtp_server smtp.sinoservices.com
   smtp_connect_timeout 30
   router_id Mysql_Breakdown_Notification  #the master and backup must have the same router id
}
 
vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 56  
    priority 101
    advert_int 1
    authentication {  
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.0.101
    }
}
 
virtual_server 192.168.0.101 3307 {
     delay_loop 2   
     lb_algo wrr   
     lb_kind DR    
     persistence_timeout 60
     protocol TCP
     real_server 192.168.0.91 3307 {
     weight 3
     notify_down /opt/chk_haproxy.sh
     TCP_CHECK {
     connect_timeout 10    
     nb_get_retry 3      
     delay_before_retry 3   
     connect_port 3307
    }
  }
}

vrrp_script chk_http_port {
    script "/opt/chk_haproxy.sh"
    interval 2
    weight 2
}

track_script {
    chk_http_port
}

 

(2)backup配置文件

global_defs {
    notification_email {
        mona.lai@sinoservices.com   //receiver email
   }
   notification_email_fromkobe.lv@sinoservices.com   //sender email
   smtp_server smtp.sinoservices.com
   smtp_connect_timeout 30
   router_id Mysql_Breakdown_Notification  #the master and backup must have the same router id
}
 
vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 56  
    priority 99
    advert_int 1
    authentication {  
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.0.101
    }
}
 
virtual_server 192.168.0.101 3307 {
     delay_loop 2   
     lb_algo wrr   
     lb_kind DR    
     persistence_timeout 60
     protocol TCP
     real_server 192.168.0.91 3307 {
     weight 3
     notify_down /opt/chk_haproxy.sh
     TCP_CHECK {
     connect_timeout 10    
     nb_get_retry 3      
     delay_before_retry 3   
     connect_port 3307
    }
  }
}

vrrp_script chk_http_port {
    script "/opt/chk_haproxy.sh"
    interval 2
    weight 2
}

track_script {
    chk_http_port
}

 

五、啓動keepalived

前後在主、從服務器上啓動keepalived:,命令:/etc/init.d/keepalived start
在主服務器上查看是否已經綁定了虛擬IP,命令: ip addr

六、設置腳本,讓keepalive監控haproxy的狀態

監控腳本:

#!/bin/bash

if [ $(ps -C haproxy --no-header | wc -l) -eq 0 ];then

  haproxy -f /etc/haproxy/haproxy.cfg

fi

sleep 3

if [ $(ps -C haproxy --no-header | wc -l) -eq 0 ];then

  /etc/init.d/keepalived stop

fi

 

七、測試無誤後,重啓MySQL、Haproxy、Keepalived,順序依次爲MySQL、Haproxy、Keepalived

啓動命令:service mysql restart

killall -9 haproxy   -> haproxy -f /var/haproxy/conf/haproxy.con

/etc/init.d/keepalived restart

4、MySQL雙主(主主)架構方案

在企業中,數據庫高可用一直是企業的重中之重,中小企業不少都是使用mysql主從方案,一主多從,讀寫分離等,可是單主存在單點故障,從庫切換成主庫須要做改動。所以,若是是雙主或者多主,就會增長mysql入口,增長高可用。不過多主須要考慮自增加ID問題,這個須要特別設置配置文件,好比雙主,可使用奇偶,總之,主之間設置自增加ID相互不衝突就能完美解決自增加ID衝突問題。

主從同步複製原理

在開始以前,咱們先來了解主從同步複製原理。

複製分紅三步:

1. master將改變記錄到二進制日誌(binary log)中(這些記錄叫作二進制日誌事件,binary log events);

2. slave將master的binary log events拷貝到它的中繼日誌(relay log);

3. slave重作中繼日誌中的事件,將改變反映它本身的數據。

下圖描述了這一過程:

 


該過程的第一部分就是master記錄二進制日誌。在每一個事務更新數據完成以前,master在二日誌記錄這些改變。MySQL將事務串行的寫入二進制日誌,即便事務中的語句都是交叉執行的。在事件寫入二進制日誌完成後,master通知存儲引擎提交事務。

下一步就是slave將master的binary log拷貝到它本身的中繼日誌。首先,slave開始一個工做線程——I/O線程。I/O線程在master上打開一個普通的鏈接,而後開始binlog dump process。Binlog dump process從master的二進制日誌中讀取事件,若是已經跟上master,它會睡眠並等待master產生新的事件。I/O線程將這些事件寫入中繼日誌。

SQL slave thread處理該過程的最後一步。SQL線程從中繼日誌讀取事件,更新slave的數據,使其與master中的數據一致。只要該線程與I/O線程保持一致,中繼日誌一般會位於OS的緩存中,因此中繼日誌的開銷很小。

此外,在master中也有一個工做線程:和其它MySQL的鏈接同樣,slave在master中打開一個鏈接也會使得master開始一個線程。

MySQL5.6之前的版本複製過程有一個很重要的限制——複製在slave上是串行化的,也就是說master上的並行更新操做不能在slave上並行操做。MySQL5.6版本參數slave-parallel-workers=1表示啓用多線程功能。

MySQL5.6開始,增長了一個新特性,是加入了全局事務ID (GTID) 來強化數據庫的主備一致性,故障恢復,以及容錯能力。

官方文檔:http://dev.mysql.com/doc/refman/5.6/en/replication-gtids.html

MySQL雙主(主主)架構方案思路是:

1.兩臺mysql均可讀寫,互爲主備,默認只使用一臺(masterA)負責數據的寫入,另外一臺(masterB)備用;

2.masterA是masterB的主庫,masterB又是masterA的主庫,它們互爲主從;

3.兩臺主庫之間作高可用,能夠採用keepalived等方案(使用VIP對外提供服務);

4.全部提供服務的從服務器與masterB進行主從同步(雙主多從);

5.建議採用高可用策略的時候,masterA或masterB均不因宕機恢復後而搶佔VIP(非搶佔模式);

這樣作能夠在必定程度上保證主庫的高可用,在一臺主庫down掉以後,能夠在極短的時間內切換到另外一臺主庫上(儘量減小主庫宕機對業務形成的影響),減小了主從同步給線上主庫帶來的壓力;

可是也有幾個不足的地方:

1.masterB可能會一直處於空閒狀態(能夠用它當從庫,負責部分查詢);

2.主庫後面提供服務的從庫要等masterB先同步完了數據後才能去masterB上去同步數據,這樣可能會形成必定程度的同步延時;

架構的簡易圖以下:

 


主主環境(這裏只介紹2臺主的配置方案):

1.CentOS 6.8 64位2臺:masterA(192.168.10.11),masterB(192.168.10.12)

2.官方Mysql5.6版本

搭建過程:

1.安裝MySQL服務(建議源碼安裝)

1.1 yum安裝依賴包

yum -yinstall make gcc gcc-c++  ncurses-devel bison openssl-devel

1.2 添加MySQL所須要的用戶和組

groupadd -g 27 mysql

adduser -u 27 -g mysql -s /sbin/nologin mysql

1.3 下載MySQL源碼包

mkdir -p /data/packages/src

cd /data/packages/wget http://distfiles.macports.org/cmake/cmake-3.2.3.tar.gzwget http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.34.tar.gz

1.4 建立mysql數據目錄

mkdir -p /usr/local/mysql/data

1.5 解壓編譯安裝cmake、MySQL

cd /data/packages/srctar -zxvf ../cmake-3.2.3.tar.gz

cd cmake-3.2.3/

./bootstrap

gmakemake install

cd ../tar xf  mysql-5.6.34.tar.gz

cd mysql-5.6.34

cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DSYSCONFDIR=/etc \-DWITH_SSL=bundled -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci \-DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_MYISAM_STORAGE_ENGINE=1 \-DMYSQL_TCP_PORT=3306 -DMYSQL_UNIX_ADDR=/tmp/mysql.sock \-DMYSQL_DATADIR=/usr/local/mysql/datamake &&make install

 

1.6 添加開機啓動腳本

cp support-files/mysql.server /etc/rc.d/init.d/mysqld

1.7 添加masterA配置文件/etc/my.cnf

[client]

port = 3306

socket = /tmp/mysql.sock

 

[mysqld]

basedir = /usr/local/mysql

port = 3306

socket = /tmp/mysql.sock

datadir = /usr/local/mysql/data

pid-file = /usr/local/mysql/data/mysql.pid

log-error = /usr/local/mysql/data/mysql.err

 

server-id = 1

auto_increment_offset = 1

auto_increment_increment = 2                                            #奇數ID

 

log-bin = mysql-bin                                                     #打開二進制功能,MASTER主服務器必須打開此項

binlog-format=ROW

binlog-row-p_w_picpath=minimal

log-slave-updates=true

gtid-mode=on

enforce-gtid-consistency=true

master-info-repository=TABLE

relay-log-info-repository=TABLEsync-master-info=1

slave-parallel-workers=0

sync_binlog=0

binlog-checksum=CRC32

master-verify-checksum=1

slave-sql-verify-checksum=1

binlog-rows-query-log_events=1

#expire_logs_days=5

max_binlog_size=1024M                                                   #binlog單文件最大值

 

replicate-ignore-db = mysql                                             #忽略不一樣步主從的數據庫

replicate-ignore-db = information_schema

replicate-ignore-db = performance_schema

replicate-ignore-db = test

replicate-ignore-db = zabbix

 

max_connections = 3000

max_connect_errors = 30

 

skip-character-set-client-handshake                                     #忽略應用程序想要設置的其餘字符集

init-connect='SET NAMES utf8'                                           #鏈接時執行的SQL

character-set-server=utf8                                               #服務端默認字符集

wait_timeout=1800                                                       #請求的最大鏈接時間

interactive_timeout=1800                                                #和上一參數同時修改纔會生效

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES                     #sql模式

max_allowed_packet = 10M

bulk_insert_buffer_size = 8M

query_cache_type = 1

query_cache_size = 128M

query_cache_limit = 4M

key_buffer_size = 256M

read_buffer_size = 16K

 

skip-name-resolve

slow_query_log=1

long_query_time = 6

slow_query_log_file=slow-query.log

innodb_flush_log_at_trx_commit = 2

innodb_log_buffer_size = 16M

 

[mysql]

no-auto-rehash

 

[myisamchk]

key_buffer_size = 20M

sort_buffer_size = 20M

read_buffer = 2M

write_buffer = 2M

 

[mysqlhotcopy]

interactive-timeout

 

[mysqldump]

quick

max_allowed_packet = 16M

 

[mysqld_safe]

1.8 特別參數說明

log-slave-updates = true     #將複製事件寫入binlog,一臺服務器既作主庫又作從庫此選項必需要開啓

#masterA自增加ID

auto_increment_offset = 1

auto_increment_increment = 2                                            #奇數ID

#masterB自增長ID

auto_increment_offset = 2

auto_increment_increment = 2                                            #偶數ID

1.9 添加masterB配置文件/etc/my.cnf

[client]

port = 3306

socket = /tmp/mysql.sock

 

[mysqld]

basedir = /usr/local/mysql

port = 3306

socket = /tmp/mysql.sock

datadir = /usr/local/mysql/data

pid-file = /usr/local/mysql/data/mysql.pid

log-error = /usr/local/mysql/data/mysql.err

 

server-id = 2

auto_increment_offset = 2

auto_increment_increment = 2                                            #偶數ID

 

log-bin = mysql-bin                                                     #打開二進制功能,MASTER主服務器必須打開此項

binlog-format=ROW

binlog-row-p_w_picpath=minimal

log-slave-updates=true

gtid-mode=on

enforce-gtid-consistency=true

master-info-repository=TABLE

relay-log-info-repository=TABLEsync-master-info=1

slave-parallel-workers=0

sync_binlog=0

binlog-checksum=CRC32

master-verify-checksum=1

slave-sql-verify-checksum=1

binlog-rows-query-log_events=1

#expire_logs_days=5

max_binlog_size=1024M                                                   #binlog單文件最大值

 

replicate-ignore-db = mysql                                             #忽略不一樣步主從的數據庫

replicate-ignore-db = information_schema

replicate-ignore-db = performance_schema

replicate-ignore-db = test

replicate-ignore-db = zabbix

 

max_connections = 3000

max_connect_errors = 30

 

skip-character-set-client-handshake                                     #忽略應用程序想要設置的其餘字符集

init-connect='SET NAMES utf8'                                           #鏈接時執行的SQL

character-set-server=utf8                                               #服務端默認字符集

wait_timeout=1800                                                       #請求的最大鏈接時間

interactive_timeout=1800                                                #和上一參數同時修改纔會生效

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES                     #sql模式

max_allowed_packet = 10M

bulk_insert_buffer_size = 8M

query_cache_type = 1

query_cache_size = 128M

query_cache_limit = 4M

key_buffer_size = 256M

read_buffer_size = 16K

 

skip-name-resolve

slow_query_log=1

long_query_time = 6

slow_query_log_file=slow-query.log

innodb_flush_log_at_trx_commit = 2

innodb_log_buffer_size = 16M

 

[mysql]

no-auto-rehash

 

[myisamchk]

key_buffer_size = 20M

sort_buffer_size = 20M

read_buffer = 2M

write_buffer = 2M

 

[mysqlhotcopy]

interactive-timeout

 

[mysqldump]

quick

max_allowed_packet = 16M

 

[mysqld_safe]

1.10 初始化MySQL

cd /usr/local/mysql

scripts/mysql_install_db --user=mysql

1.11 爲啓動腳本賦予可執行權限並啓動MySQL

chmod +x /etc/rc.d/init.d/mysqld/etc/init.d/mysqld start

2.配置主從同步

2.1 添加主從同步帳戶

masterA上:

mysql> grant replication slaveon *.* to 'repl'@'192.168.10.12' identifiedby '123456';

mysql> flushprivileges;

masterB上:

mysql> grant replication slaveon *.* to 'repl'@'192.168.10.11' identifiedby '123456';

mysql> flushprivileges;

2.2 查看主庫的狀態

masterA上:


mysql> show master status;

+------------------+----------+--------------+------------------+-------------------+

| File             | Position| Binlog_Do_DB| Binlog_Ignore_DB| Executed_Gtid_Set|

+------------------+----------+--------------+------------------+-------------------+

| mysql-bin.000003 |      120 |              |                  |                   |

+------------------+----------+--------------+------------------+-------------------+

1 rowin set (0.00 sec)


masterB上


mysql> show master status;

+------------------+----------+--------------+------------------+-------------------+

| File             | Position| Binlog_Do_DB| Binlog_Ignore_DB| Executed_Gtid_Set|

+------------------+----------+--------------+------------------+-------------------+

| mysql-bin.000003 |      437 |              |                  |                   |

+------------------+----------+--------------+------------------+-------------------+

1 rowin set (0.00 sec)


2.3 配置同步信息:

masterA上:


mysql> change masterto master_host='192.168.10.12',master_port=3306,master_user='repl',master_password='123456',master_log_file='mysql-bin.000003',master_log_pos=437;

 

mysql> start slave;

 

mysql> show slave status\G;


 

顯示有以下狀態則正常:

Slave_IO_Running: Yes

 

Slave_SQL_Running: Yes

masterB上:

#本人是測試環境,能夠保證沒數據寫入,不然須要的步驟是:先masterA鎖表-->masterA備份數據-->masterA解鎖表-->masterB導入數據-->masterB設置主從-->查看主從


mysql> change masterto master_host='192.168.10.11',master_port=3306,master_user='repl',master_password='123456',master_log_file='mysql-bin.000003',master_log_pos=120;

 

start slave;

 

mysql> show slave status\G;


顯示有以下狀態則正常:

Slave_IO_Running: Yes

 

Slave_SQL_Running: Yes

3.測試主從同步

3.1 在masterA上建立一個數據庫測試同步效果


mysql> show databases;

+--------------------+

| Database           |

+--------------------+

| information_schema|

| mysql              |

| performance_schema|

| test               |

+--------------------+

4 rowsin set (0.00 sec)

 

mysql> create database test01;

 

Query OK, 1 row affected (0.00 sec)

 

mysql> show databases;

+--------------------+

| Database           |

+--------------------+

| information_schema|

| mysql              |

| performance_schema|

| test               |

| test01             |

+--------------------+

5 rowsin set (0.00 sec)

 

mysql> quit

 

Bye

[root@masterA data]#


3.2 到masterB查看是否已經同步建立數據庫


mysql> show databases;

+--------------------+

| Database           |

+--------------------+

| information_schema|

| mysql              |

| performance_schema|

| test               |

| test01             |

+--------------------+

5 rowsin set (0.00 sec)

 

mysql> quit

 

Bye

[root@masterB data]#


4.開啓MySQL5.6的GTID功能

masterA和masterB分別執行以下命令:


mysql> stop slave;

 

Query OK, 0 rows affected (0.00 sec)

 

mysql> change masterto MASTER_AUTO_POSITION=1;

 

Query OK, 0 rows affected (0.01 sec)

 

mysql> start slave;

 

Query OK, 0 rows affected (0.00 sec)


5.遇到的問題

一種主從報錯折騰了我半天:

Last_IO_Errno: 1236

Last_IO_Error: Got fatal error 1236 from master when reading data from binary log: 'Could not open log file'

後面修改主從同步相關參數,確認緣由是my.cnf增長了以下參數:

log-bin = mysql-bin

relay-log = mysql-bin

 


從正常主主同步時的二進制日誌文件顯示,有2套二進制日誌。所以推斷上面2個參數致使不能產生2套二進制文件,故致使二進制文件錯亂和丟失。

 

 

5、附錄:

MySQL忘記了root密碼,使用skip-grant-tables方式啓動後,用set password的方式修改root密碼時遇到錯誤

ERROR 1290 (HY000)

1.以skip-grant-tables方式啓動mysql

C:\Users\>mysqld --skip-grant-tables
130411 10:09:30 [Warning] '--default-character-set' is deprecated and will be removed in a future re
lease. Please use '--character-set-server' instead.
130411 10:09:30 [Warning] Changed limits: max_open_files: 2048  max_connections: 700  table_cache: 6
69

 

 2.用root用戶登陸,不用輸入密碼

C:\Users\>mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.54-community-log MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

3.用set password方式修改root密碼遇到錯誤ERROR 1290 (HY000)

mysql> set password for root@'localhost'=PASSWORD('12345');
ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot exe
cute this statement

4. 用update方式修改root密碼正常
mysql> update mysql.user set password=password('12345') where user='root' and host='localhost';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

5.刷新權限

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

看來以skip-grant-tables方式啓動mysql後,不能用set password的方式修改root密碼

相關文章
相關標籤/搜索