MySQL讀寫分離高可用集羣及讀操做負載均衡(Centos7)

[toc]html

概述

本項目解決了MySQL讀操做頻繁給數據庫服務器形成的巨大壓力,和寫操做數據庫服務器的高可用性以及數據存儲的問題。java

兩臺寫的數據庫服務器之間使用heartbeat心跳線,和drdb技術構建網絡raid1存儲,搭建nfs直接綁定VIP,對客戶端來講透明,方便,切換時耗時較短mysql

keepalived和heartbeat對比

網上找了很多資料,簡單整理下linux

  • keepalived使用配置很簡單
  • heartbeat的功能更強大
  • 協議不一樣:keepalived使用VRRP協議通訊,heartbeat使用心跳,能夠經過以太網絡,串口通訊。
  • 都是要自定義腳原本和業務進行關聯

總結下:Keepalived使用的vrrp協議方式,虛擬路由冗餘協議 (Virtual Router Redundancy Protocol,簡稱VRRP);
Heartbeat是基於主機或網絡的服務的高可用方式;
keepalived的目的是模擬路由器的雙機;
heartbeat的目的是用戶service的雙機;
lvs的高可用建議用keepavlived;
業務的高可用建議heartbeatgit

1、環境

所有都是CentOS7.5操做系統,而且已經關閉防火牆和selinux,須要使用配置放行策略github

主機名 IP地址 擔任角色
dbmaster 192.168.111.7 寫操做服務器master,已經搭建完成了drbd,heartbeat
dbbackup 192.168.111.8 寫操做服務器backup,已經搭建完成了drbd,heartbeat
lvs1 192.168.111.3 lvs代理master,搭建lvs和keepalived
lvs2 192.168.111.4 lvs代理backup,搭建lvs和keepalived
readMySQL1 192.168.111.5 讀操做服務器
readMySQL2 192.168.111.6 讀操做服務器和readMySQL之間互相負載均衡
web 192.168.111.9 web服務器搭建Tomcat進行測試讀寫分離;爲了節省資源amoeba也是在這臺機器配置
heartbeatVIP 192.168.111.100
keepalivedVIP 192.168.111.200
  • 搭建思路

2、部署

部署lvs代理和keepalived

lvs1:web

[root@localhost ~]# yum -y install ipvsadm keepalived
[root@localhost ~]# > /etc/keepalived/keepalived.conf
#清空自帶的配置

[root@localhost ~]# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived 
global_defs { 
router_id lvs_clu_2
#設置lvs的id,在一個網絡內應該是惟一的 
} 
virrp_sync_group Prox { 
group { 
mail 
} 
} 
vrrp_instance mail { 
#vrrp實例定義部分 
state MASTER 
#設置lvs的狀態,MASTER和BACKUP兩種,必須大寫 
interface ens32
#設置對外服務的接口 
lvs_sync_daemon_interface ens32
 #負載均衡器之間的監控接口,相似於 HA HeartBeat的心跳線。但它的機制優於 Heartbeat,由於它沒有「裂腦」這個問題,它是以優先級這個機制來規避這個麻煩的。在DR 模式中,lvs_sync_daemon_inteface 與服務接口 interface 使用同一個網絡接口。  
virtual_router_id 50 
#設置虛擬路由標示,這個標示是一個數字,同一個vrrp實例使用惟一標示 
priority 80 
#定義優先級,數字越大優先級越高,在一個vrrp——instance下,master的優先級必須大於backup 
advert_int 1 
#設定master與backup負載均衡器之間同步檢查的時間間隔,單位是秒 
authentication { 
#設置驗證類型和密碼 
auth_type PASS 
#主要有PASS和AH兩種 
auth_pass 1111 
#驗證密碼,同一個vrrp_instance下MASTER和BACKUP密碼必須相同 
} 
virtual_ipaddress { 
192.168.111.200 
#設置虛擬Vip地址,能夠設置多個,每行一個 
} 
} 
virtual_server 192.168.111.200 3306 { 
#設置虛擬VIP服務器,須要指定虛擬ip和服務端口 
delay_loop 6 
#健康檢查時間間隔 
lb_algo wrr 
 #負載均衡調度算法
lb_kind DR 
#負載均衡轉發規則 
persistence_timeout 0 
#設置會話保持時間,對動態網頁很是有用 
protocol TCP 
#指定轉發協議類型,有TCP和UDP兩種 
nat_mask 255.255.255.0  
real_server 192.168.111.5 3306 { 
#配置服務器節點1,須要指定real server的真實IP地址和端口 
weight 1  
#設置權重,數字越大權重越高 
TCP_CHECK { 
#realserver的狀態監測設置部分單位秒 
connect_timeout 3 
#超時時間 
nb_get_retry 3 
#重試次數 
delay_before_retry 3 
#重試間隔 
connect_port 3306 
#監測端口 
} 
} 
real_server 192.168.111.6 3306 { 
weight 1   
TCP_CHECK { 
connect_timeout 3 
nb_get_retry 3 
delay_before_retry 3 
connect_port 3306
} 
} 
}

lvs2:算法

[root@localhost ~]# yum -y install ipvsadm keepalived
[root@localhost ~]# > /etc/keepalived/keepalived.conf
[root@localhost ~]# vim /etc/keepalived/keepalived.conf
! Configuration File for keepalived 
global_defs { 
router_id lvs_clu_1 
} 
virrp_sync_group Prox { 
group { 
mail 
} 
} 
vrrp_instance mail { 
state BACKUP
interface ens32
lvs_sync_daemon_interface ens32
virtual_router_id 50 
priority 70 
advert_int 1 
authentication { 
auth_type PASS 
auth_pass 1111 
} 
virtual_ipaddress { 
192.168.111.200 
} 
} 
virtual_server 192.168.111.200 3306 { 
delay_loop 6 
lb_algo wrr 
lb_kind DR 
persistence_timeout 0 
protocol TCP 
nat_mask 255.255.255.0  
real_server 192.168.111.5 3306 { 
weight 1  
TCP_CHECK { 
connect_timeout 3 
nb_get_retry 3 
delay_before_retry 3 
connect_port 3306 
} 
} 
real_server 192.168.111.6 3306 { 
weight 1   
TCP_CHECK { 
connect_timeout 3 
nb_get_retry 3 
delay_before_retry 3 
connect_port 3306
} 
} 
}

注意備機的權重和routeid 配置負載調度器 配置虛擬IP地址(VIP)採用虛擬接口的方式(ens32:0),爲網卡ens32綁定VIP址,以便響應羣集訪問。sql

[root@localhost ~]# ifconfig ens32:0 192.168.111.200 netmask 255.255.255.0
[root@localhost ~]# ifconfig ens32:0
ens32:0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.111.200 netmask 255.255.255.0 broadcast 192.168.111.255
#兩個lvs都須要配置


配置節點服務器
使用 DR 模式時,節點服務器也須要配置 VIP 地址,並調整內核的 ARP響應參數以阻止更新 VIP 的 MAC 地址,避免發生衝突。除此以外,Web 服務的配置與 NAT 方式相似。
在每一個節點服務器,一樣須要有 VIP 地址 192.168.111.200,但此地址僅用做發送 Web響應數據包的源地址,並不須要監聽客戶機的訪問請求(改由調度器監聽並分發)。所以使用虛擬接口 lo:0 來承載 VIP 地址,併爲本機添加一條路由記錄,將訪問 VIP 的數據限制在本地以免通訊紊亂。
[root@localhost ~]# ifconfig lo:0 192.168.111.200 netmask 255.255.255.255
[root@localhost ~]# ifconfig lo:0
lo:0: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 192.168.111.200  netmask 255.255.255.255
        loop  txqueuelen 1000  (Local Loopback)

[root@localhost ~]# route add -host 192.168.111.200 dev lo:0
#臨時添加了該路由,也可寫入配置文件須要重啓網卡,兩個節點都作


節點服務器調整/proc相應參數

[root@localhost ~]# vim /etc/sysctl.conf 
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.default.arp_ignore = 1
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.lo.arp_ignore = 1
net.ipv4.conf.lo.arp_announce = 2
#arp_ignore=1,系統只回答目的 IP 爲是本地 IP 的包。也就是對廣播包不作響應。
#rp_announce=2,系統忽略 IP 包的源地址(source address),而根據目標主機(target host),選擇本地地址。
[root@localhost ~]# sysctl -p

MySQL+heartbeat+drbd的部署

參考筆者另外一篇文檔來部署drbd及heartbeat數據庫

基於drbd和heartbeat部署成功的基礎和MySQL進行結合

mkdir /mysqlda
#新的MySQL數據存放目錄

[root@dbmaster ~]# vim /usr/local/heartbeat/etc/ha.d/haresources 
    dbmaster IPaddr::192.168.111.100/24/ens32 drbddisk::r0 Filesystem::/dev/drbd0::/mysqlda::ext4 killmy
#將資源配置修改成如上

[root@dbmaster ~]# vim /usr/local/heartbeat/etc/ha.d/resource.d/killmy 
    pkill -9 mariadb; systemctl restart mariadb; exit 0
#編寫相應的腳本,heartbeatVIP切換時會執行改腳本

chmod +x /usr/local/heartbeat/etc/ha.d/resource.d/killmy

[root@dbmaster ~]# yum -y install mariadb*
[root@dbmaster ~]# ip a | grep ens32:0
    inet 192.168.111.100/24 brd 192.168.111.255 scope global secondary ens32:0
[root@dbmaster ~]# df | grep drbd
/dev/drbd0               1014612    2568   943288    1% /mysqlda
#能夠看到個人VIP和drbd的控制權如今都在dbmaster主機上

systemctl restart heartbeat
#各自從新加載heartbeat,卡住的話直接kill掉再重啓

[root@dbmaster ~]# cp -Rp /var/lib/mysql/ /mysqlda/
#舊的數據目錄複製到新的數據目錄

[root@dbmaster ~]# vim /etc/my.cnf
[mysqld]
datadir=/mysqlda/mysql
#這裏更改數據目錄
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mariadb according to the
# instructions in http://fedoraproject.org/wiki/Systemd
user=mysql
server-id=1
log-bin
#二進制日誌開啓
[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid

#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
備機配置同樣,記得server-id修改成不一樣的

dbbackup上重啓mariadb

  • 可能遇到以下報錯,可是小弟這裏目前沒有發現。
[root@dbmaster ~]# systemctl restart mariadb
/usr/libexec/mysqld: Table 'mysql.plugin' doesn't exist
161121 14:45:35 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
161121 14:45:36 [ERROR] Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist
161121 14:45:36 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

由於我以前第一次啓動的時候datadir是/var/lib/mysql,更改配置文件後,從新啓動時找不到對應 庫文件,雖然我已經把/var/lib/mysql/* 複製到了/database/mysql下面

解決方法就是從新執行mysql_install_db來解決問題。

[root@dbmaster ~]# mysql_install_db --user=mysql
  • 簡單測試
[root@dbmaster mysql]# ls
aria_log.00000001  ibdata1      ib_logfile1         mariadb-bin.index  mysql.sock          test
aria_log_control   ib_logfile0  mariadb-bin.000001  mysql              performance_schema
#跟後面作個對比

[root@dbmaster mysql]# mysql

MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> update user set password=password('123456') where user='root' and host='localhost';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

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

MariaDB [mysql]> exit
Bye

#這裏順便更改下用戶的默認密碼

MariaDB [(none)]> create database test1;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> use test1;

MariaDB [test1]> create table t1 (id int,name varchar(20));
Query OK, 0 rows affected (0.01 sec)

[root@dbmaster ~]# ls /mysqlda/mysql/
aria_log.00000001   ibdata1             ib_logfile1         mariadb-bin.index   mysql.sock          test/               
aria_log_control    ib_logfile0         mariadb-bin.000001  mysql/              performance_schema/ test1/              
[root@dbmaster ~]# ls /mysqlda/mysql/test1/
db.opt  t1.frm  
[root@dbmaster ~]# ls /mysqlda/mysql/test1/
db.opt  t1.frm
  • 切換VIP看數據
[root@dbmaster mysql]# systemctl stop heartbeat.service
#master上停掉心跳

[root@dbbackup ~]# netstat -anpt | grep mysqld
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      6873/mysqld         
#備上查看MySQL,我原來沒開,切過來VIP ,heartbeat經過腳本執行的

[root@dbbackup ~]# ls /mysqlda/mysql/
aria_log.00000001   ib_logfile0         mariadb-bin.000002  mariadb-bin.index   performance_schema/ 
aria_log_control    ib_logfile1         mariadb-bin.000003  mysql/              test/               
ibdata1             mariadb-bin.000001  mariadb-bin.000004  mysql.sock          test1/              
[root@dbbackup ~]# ls /mysqlda/mysql/test1/
db.opt  t1.frm
#備上查看,暫時準確無誤

MySQL主從複製

Mysql的複製是異步複製,即從一個Mysql實例或者端口(成爲master)複製到另外一個Mysql實例或者端口(成爲slave)。複製操做有3個進程實現的,其中兩個進程(Sql進程和IO進程)在Slave上,另外一個進程在master(binlog dump)上。

  • 實現複製前提須要打開log-bin二進制日誌功能這是由於整個複製其實是slave從Master端獲取該更新操做的日誌,將其傳輸到本地並寫到本地文件中,而後在讀取本地內容執行日誌中所記錄的更新操做。
master操做:
MariaDB [(none)]> grant replication slave on *.* to 'rep'@'192.168.111.%' identified by'123456';
Query OK, 0 rows affected (0.00 sec)
#受權用戶權限

show grants for rep@'192.168.111.%'
#查看權限

MariaDB [(none)]> flush privileges;

先採用打包的方式,進行一次徹底備份
MariaDB [(none)]> flush tables with read lock;
#鎖表
MariaDB [(none)]> reset master
    -> ;
Query OK, 0 rows affected (0.02 sec)
MariaDB [test1]> create table t2 (id int,name varchar(20));
ERROR 1223 (HY000): Can't execute the query because you have a conflicting read lock
#鎖表完成了

而後另外打開一個終端操做

[root@dbbackup ~]# cd /mysqlda/mysql/

[root@dbbackup mysql]# tar zcvf mysqlsql`date +%F`.tar.gz ib* mysql* test/ test1/
#將須要的文件打包壓縮,也能夠選擇經過mysqldump導出數據庫。

[root@dbbackup mysql]# scp -r mysqlsql2019-05-16.tar.gz root@readMySQL1:/opt/
root@readmysql1's password: 
mysqlsql2019-05-16.tar.gz                                                                                         100%  572KB  42.5MB/s   00:00    
[root@dbbackup mysql]# scp -r mysqlsql2019-05-16.tar.gz root@readMySQL2:/opt/
root@readmysql2's password: 
mysqlsql2019-05-16.tar.gz                                                                                         100%  572KB   3.9MB/s   00:00 
#複製到讀操做服務器上

MariaDB [(none)]> show master status;
+--------------------+----------+--------------+------------------+
| File               | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+--------------------+----------+--------------+------------------+
| mariadb-bin.000001 |      245 |              |                  |
+--------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
#查看狀態,讀服務器根據二進制日誌備份會須要。
  • 讀服務器的操做
yum -y install mariadb*

tar zxf /opt/mysqlsql2019-05-16.tar.gz -C /var/lib/mysql/
#解壓到指定的數據目錄,我這裏是默認目錄,-C指定路徑

[root@localhost ~]# ls /var/lib/mysql/
ibdata1  ib_logfile0  ib_logfile1  mysql  test  test1

[root@localhost ~]# vim /etc/my.cnf
[mysqld]
server-id = 4
#每一個id都不一樣

[root@localhost ~]# systemctl start mariadb

[root@localhost ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 83
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> 
MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> update user set password=password('123456') where user='root' and host='localhost';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

MariaDB [mysql]> exit
Bye
#更改下默認密碼

[root@localhost ~]# mysql -u root -p123456 -e "change master to master_host='192.168.111.100',master_user='rep',master_password='123456',master_log_file='mariadb-bin.000001',master_log_pos=245;"
[root@localhost ~]# mysql -u root -p123456 -e "start slave;"

[root@localhost ~]# mysql -u root -p123456 -e"show slave status\G;"
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.111.100
                  Master_User: rep
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mariadb-bin.000001
          Read_Master_Log_Pos: 1585
               Relay_Log_File: mariadb-relay-bin.000002
                Relay_Log_Pos: 531
        Relay_Master_Log_File: mariadb-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1585
              Relay_Log_Space: 827
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 2

重點關注這兩項:
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
爲yes基本上主從複製算是成功了
  • MySQL主從複製及VIP切換測試
VIP所在機器操做以下:
MariaDB [test1]> create table tabletest (id int,name varchar(20));

讀操做服務器查看:
MariaDB [(none)]> use test1;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [test1]> show tables;
+-----------------+
| Tables_in_test1 |
+-----------------+
| t1              |
| tabletest       |
+-----------------+
2 rows in set (0.00 sec)

VIP切換測試

[root@dbbackup ~]# ip a| grep ens32:0
    inet 192.168.111.100/24 brd 192.168.111.255 scope global secondary ens32:0
[root@dbbackup ~]# systemctl stop heartbeat.service 

[root@dbmaster ~]# ip a| grep ens32:
2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.111.100/24 brd 192.168.111.255 scope global secondary ens32:1
#另外一臺機器查看VIP是否轉移過來

[root@dbmaster ~]# mysql -u root -p123456

MariaDB [(none)]> use test1;

[test1]> create table tabletest2 (id int,name varchar(20));
Query OK, 0 rows affected (0.01 sec)

#建立表進行,主從複製測試

讀操做服務器查看:
[root@localhost ~]# mysql -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 168
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> use test1;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [test1]> show tables;
+-----------------+
| Tables_in_test1 |
+-----------------+
| t1              |
| tabletest       |
| tabletest2      |
+-----------------+
3 rows in set (0.00 sec)

主從複製告一段落

web服務器及amoeba配置

  • 這裏安裝Tomcat作以示範
[root@web ~]# ls
anaconda-ks.cfg  apache-tomcat-8.5.16.tar.gz  initial-setup-ks.cfg  jdk-8u191-linux-x64.tar.gz

安裝tar包jdk
[root@web ~]# rm -rf /usr/bin/java
[root@web ~]# tar zxf jdk-8u191-linux-x64.tar.gz 
[root@web ~]# mv jdk1.8.0_191/ /usr/local/java8
[root@web ~]# echo "export JAVA_HOME=/usr/local/java8" >> /etc/profile
[root@web ~]# echo "PATH=$PATH:/usr/local/java8/bin" >> /etc/profile
[root@web ~]# source /etc/profile
[root@web ~]# java -version
java version "1.8.0_191"
Java(TM) SE Runtime Environment (build 1.8.0_191-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)

[root@web ~]# /usr/local/tomcat8/bin/startup.sh 
Using CATALINA_BASE:   /usr/local/tomcat8
Using CATALINA_HOME:   /usr/local/tomcat8
Using CATALINA_TMPDIR: /usr/local/tomcat8/temp
Using JRE_HOME:        /usr/local/java8
Using CLASSPATH:       /usr/local/tomcat8/bin/bootstrap.jar:/usr/local/tomcat8/bin/tomcat-juli.jar
Tomcat started.

客戶端訪問 http://192.168.111.9:8080 進行測試

  • 安裝配置amoeba 常見讀寫分離方案概述:
  1. 基於程序代碼內部實現
    在代碼中根據 select,insert進行路由分類,這類方法也是目前生產環境應用最普遍的,優勢是性能好,由於在程序代碼中實現,不須要曾加額外的設備做爲硬件開支,缺點是須要開發人員來實現,運維人員無從下手。
  2. 基於中間代理層實現
    代理通常位於客戶端和服務器之間,代理服務器接到客戶端請求後經過判斷後轉發到後端數據庫,表明性程序: (1)mysql-proxy 爲 mysql 開發早期開源項目,經過其自帶的 lua 腳本進行 SQL 判斷,雖然是 mysql 的官方產品,可是 mysql 官方不建議將其應用到生產環境。 (2)Amoeba (變形蟲)由陳思儒開發,曾就任與阿里巴巴,該程序由 java 語言進行開發,阿里巴巴將其應用於生成環境,它不支持事物和存儲過程。

配置

[root@web ~]# mkdir /usr/local/amoeba
[root@web ~]# tar zxf amoeba-mysql-binary-2.2.0.tar.gz -C /usr/local/amoeba/
[root@web ~]# chmod -R 755 /usr/local/amoeba/

在負責寫操做的而且VIP所在服務器上操做以下,目的是進行受權
在兩臺負責讀操做服務器上操做以下,受權:
MariaDB [test1]> grant all on *.* to 'amoetest'@'192.168.111.%' identified by '123456';
Query OK, 0 rows affected (0.00 sec)

MariaDB [test1]> flush privileges;

回到amoeba所在服務器上:
[root@web ~]# vim /usr/local/amoeba/conf/amoeba.xml
 11     <property name="port">8066</property>
 #amoeba監聽端口
 30     <property name="user">amoeba</property>
 #給開發人員用的帳號,下文是密碼
 32     <property name="password">123456</property>
116      <property name="defaultPool">master</property>
#配置默認的數據庫節點,除了select,update,insert,delete語句都會在defaultpool上執行
119     <property name="writePool">master</property>
#配置寫操做數據庫
120     <property name="readPool">slaves</property>
#配置讀操做數據庫

[root@web ~]# vim /usr/local/amoeba/conf/dbServers.xml 
20                         <property name="port">3306</property>
#mysql端口
 23                         <property name="schema">test</property>
#amoeba控制的mysql庫名,能夠多添加幾個
26                         <property name="user">amoetest</property>
#mysql給受權的用戶名 
28                         <property name="password">123456</property>
#mysql給受權的密碼
 43         <dbServer name="master"  parent="abstractServer">
 46                         <property name="ipAddress">192.168.111.100</property>
 #定義服務器名字和amoeba.xml相對應,下面指定的IP地址指定的是寫操做高可用幾羣的VIP,以下同樣
 48         </dbServer>
 50         <dbServer name="slave"  parent="abstractServer">
 53                         <property name="ipAddress">192.168.111.200</property>
 54                 </factoryConfig>
 55         </dbServer>


另外建議註釋如下文件行,本案例中並無服務器池,對amoeba來講一個集羣即爲一臺服務器
 56         <!--
 57         <dbServer name="multiPool" virtual="true">
 58                 <poolConfig class="com.meidusa.amoeba.server.MultipleServerPool">
 59                         <!-- Load balancing strategy: 1=ROUNDROBIN , 2=WEIGHTBASED , 3=HA-->
 60                         <property name="loadbalance">1</property>
 61 
 62                         <!-- Separated by commas,such as: server1,server2,server1 -->
 63                         <property name="poolNames">server1,server2</property>
 64                 </poolConfig>
 65         </dbServer>
 66         -->

[root@web ~]# nohup /usr/local/amoeba/bin/amoeba start &
#原本到這裏就正常啓動了,接下來的報錯可能有些不會發生

[root@web ~]# cat nohup.out 
The stack size specified is too small, Specify at least 228k
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

解決
[root@web ~]# vim /usr/local/amoeba/bin/amoeba
 58 DEFAULT_OPTS="-server -Xms256m -Xmx256m -Xss256k"
 
[root@web ~]# nohup /usr/local/amoeba/bin/amoeba start &
#不出意外成功
[root@web ~]# netstat -anpt | grep 8066
tcp6       0      0 :::8066                 :::*                    LISTEN      65920/java  
#端口出來的慢比較
[root@web ~]# mysql -h192.168.111.9 -uamoeba -p -P8066
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
#指向amoeba的地址,用戶端口,密碼要輸入正確.這停留等待時間可能須要點,但若是配置無措,能夠鏈接的

MySQL [(none)]> use test;

No connection. Trying to reconnect...
Connection id:    185788589
Current database: *** NONE ***

Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

MySQL [test]> create table t2 (id int,name varchar(20));
Query OK, 0 rows affected (0.02 sec)

MySQL [test]> show tables;
+----------------+
| Tables_in_test |
+----------------+
| t2             |
+----------------+
#感受卡,目前不是特別順

amoeba配置文件詳解

另外一個

  • 配置Tomcat鏈接mysql(amoeba)
下載 mysql-connector-java
官網下載地址:http://dev.mysql.com/downloads/connector/j/
我用的是mysql-connector-java-3.1.14

[root@web lib]# cp mysql-connector-java-3.1.14-bin.jar /usr/local/tomcat8/lib/
#下載好的放到tomcat目錄下的lib目錄下
[root@web lib]# /usr/local/tomcat8/bin/shutdown.sh 
[root@web lib]# /usr/local/tomcat8/bin/startup.sh 

[root@web lib]# vim /usr/local/tomcat8/webapps/test/index.jsp 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
    try{
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://192.168.111.9:8066/test";
        String username="amoeba";
        String password="123456";
        Connection conn=DriverManager.getConnection(url,username,password);
        if(conn!=null){
            out.println("mysql數據庫鏈接成功!!!");
        }else{
            out.println("數據庫鏈接失敗!!!");
        }
    }catch(ClassNotFoundException e){
        e.printStackTrace();
    }
%>
%%</body>
%%</html>
#以上文件使用的時候更改相應的ip地址,及端口,我這裏直接輸入的是在amoeba上的端口,以及ip,和帳戶及密碼

#測試:瀏覽器輸入http://192.168.111.9:8080/test/index.jsp
#配置正確的話顯示輸出信息,鏈接成功

總測試

  • 部署開源站點在Tomcat上跑

jpress 官網:http://jpress.io 下載地址:https://github.com/JpressProjects/jpress

MariaDB [(none)]> create database jpress default character set utf8;
MariaDB [(none)]> grant all on jpress.* to jpress@'192.168.111.%' identified by '123456';
MariaDB [(none)]> flush privileges;
#寫操做服務器VIP所在機器上操做

#查看讀操做服務器是否同步
[root@localhost ~]# ip a | grep ens32
2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.111.5/24 brd 192.168.111.255 scope global noprefixroute ens32
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| jpress             |
| mysql              |
| test               |
| test1              |
+--------------------+
5 rows in set (0.00 sec)


[root@localhost ~]# ip a | grep ens32
2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.111.6/24 brd 192.168.111.255 scope global noprefixroute ens32
[root@localhost ~]# mysql -u root -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2829
Server version: 5.5.60-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| jpress             |
| mysql              |
| test               |
| test1              |
+--------------------+
5 rows in set (0.00 sec)

#也能夠在讀操做服務器上查看受權信息,也已經同步到本機
  • 代碼上線
[root@localhost ~]# wget https://github.com/JpressProjects/jpress/archive/0.4.0.tar.gz
[root@localhost ~]# tar xf 0.4.0.tar.gz
[root@localhost ~]# cd jpress-0.4.0/wars/
[root@localhost wars]# mv jpress-web-newest.war /usr/local/tomcat8/webapps/
[root@localhost wars]# /usr/local/tomcat8/bin/shutdown.sh 
[root@localhost wars]# /usr/local/tomcat8/bin/startup.sh 
[root@web ~]# ls /usr/local/tomcat8/webapps/
docs  examples  host-manager  jpress-web-newest  jpress-web-newest.war
#自動部署war包

[root@web ~]# vim /usr/local/amoeba/conf/dbServers.xml 
 23                         <property name="schema">jpress</property>
 24 
 25                         <!-- mysql user -->
 26                         <property name="user">jpress</property>
 27 
 28                         <property name="password">123456</property>

#改成在數據庫新受權的用戶

瀏覽器訪問http://192.168.111.9:8080/jpress-web-newest/install

[root@web ~]# /usr/local/tomcat8/bin/shutdown.sh

[root@web ~]# /usr/local/tomcat8/bin/startup.sh

查看數據庫數據同步否

[root@dbmaster ~]# ip a | grep ens32
2: ens32: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.111.7/24 brd 192.168.111.255 scope global noprefixroute ens32
    inet 192.168.111.100/24 brd 192.168.111.255 scope global secondary ens32:2


[root@dbmaster ~]# mysql -uroot -p123456
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 169
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> use jpress
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [jpress]> show tables;
+-------------------+
| Tables_in_jpress  |
+-------------------+
| jpress_attachment |
| jpress_comment    |
| jpress_content    |
| jpress_mapping    |
| jpress_metadata   |
| jpress_option     |
| jpress_taxonomy   |
| jpress_user       |
+-------------------+
8 rows in set (0.00 sec)
#正常狀況下,MySQL寫服務器,讀操做的兩臺數據應該是徹底同樣的
  • heartbeat切換測試
[root@dbmaster ~]# cat /opt/monitor_mysql.sh 
#!/bin/bash
while true
do
sleep 2
counter=$(netstat -na|grep "LISTEN"|grep "3306"|wc -l)
	if [ "${counter}" -eq 0 ]; then
	  systemctl stop heartbeat.service
	fi
done
#只是簡單測試腳本,不可應用於生產環境下
[root@dbbackup ~]# chmod +x /opt/monitor_mysql.sh 
[root@dbmaster ~]# nohup /opt/monitor_mysql.sh &
[1] 26582
[root@dbmaster ~]# nohup: 忽略輸入並把輸出追加到"nohup.out"
#VIP機器運行此腳本

接下來在VIP所在機器將mariadb關閉

等待幾秒,另外一臺查看,轉移成功

[root@web ~]# mysql -h192.168.111.100 -ujpress -p123456 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> 
別的服務器測試也沒啥問題

keepalived配置文件詳解

! Configuration File for keepalived

global_defs {
    notification_email {
        acassen@firewall.loc     #設置報警郵件地址,能夠設置多個,每行一個。
        failover@firewall.loc    #需開啓本機的sendmail服務
        sysadmin@firewall.loc
    }
    notification_email_from Alexandre.Cassen@firewall.loc  #設置郵件的發送地址
    smtp_server 127.0.0.1      #設置smtp server地址
    smtp_connect_timeout 30    #設置鏈接smtp server的超時時間
    router_id LVS_DEVEL        #表示運行keepalived服務器的一個標識。發郵件時顯示在郵件主題的信息
}

vrrp_instance VI_1 {
    state MASTER              #指定keepalived的角色,MASTER表示此主機是主服務器,BACKUP表示此主機是備用服務器
    interface enp0s3     #指定HA監測網絡的接口
    virtual_router_id 51      #虛擬路由標識,這個標識是一個數字,同一個vrrp實例使用惟一的標識。即同一vrrp_instance下,MASTER和BACKUP必須是一致的
    priority 100              #定義優先級,數字越大,優先級越高,在同一個vrrp_instance下,MASTER的優先級必須大於BACKUP的優先級
    advert_int 1              #設定MASTER與BACKUP負載均衡器之間同步檢查的時間間隔,單位是秒
    authentication {          #設置驗證類型和密碼
        auth_type PASS        #設置驗證類型,主要有PASS和AH兩種
        auth_pass 1111        #設置驗證密碼,在同一個vrrp_instance下,MASTER與BACKUP必須使用相同的密碼才能正常通訊
    }
    virtual_ipaddress {       #設置虛擬IP地址,能夠設置多個虛擬IP地址,每行一個
        192.168.137.100 
    }
}

virtual_server 192.168.137.100 80 {  #設置虛擬服務器,須要指定虛擬IP地址和服務端口,IP與端口之間用空格隔開
    delay_loop 6              #設置運行狀況檢查時間,單位是秒
    lb_algo rr                #設置負載調度算法,這裏設置爲rr,即輪詢算法
    lb_kind DR                #設置LVS實現負載均衡的機制,有NAT、TUN、DR三個模式可選
    nat_mask 255.255.255.0 
    persistence_timeout 0    #會話保持時間,單位是秒。這個選項對動態網頁是很是有用的,爲集羣系統中的session共享提供了一個很好的解決方案。
                              #有了這個會話保持功能,用戶的請求會被一直分發到某個服務節點,直到超過這個會話的保持時間。
                              #須要注意的是,這個會話保持時間是最大無響應超時時間,也就是說,用戶在操做動態頁面時,若是50秒內沒有執行任何操做
                              #那麼接下來的操做會被分發到另外的節點,可是若是用戶一直在操做動態頁面,則不受50秒的時間限制
    protocol TCP              #指定轉發協議類型,有TCP和UDP兩種

    real_server 192.168.137.5 80 { #配置服務節點1,須要指定real server的真實IP地址和端口,IP與端口之間用空格隔開
        weight 1              #配置服務節點的權值,權值大小用數字表示,數字越大,權值越高,設置權值大小能夠爲不一樣性能的服務器
                              #分配不一樣的負載,能夠爲性能高的服務器設置較高的權值,而爲性能較低的服務器設置相對較低的權值,這樣才能合理地利用和分配系統資源
  • 還有讀操做數據庫切換,關閉一臺,使用客戶端訪問測試,這裏再也不掩飾 暫時完結

總結

  1. lvs使用dr模式,並且因爲我這是測試環境,也沒有加多餘的網卡,剛開始時沒有配置/proc參數,一直出問題,我還覺得是amoeba鏈接慢呢,人家都沒連上去,都鏈接到寫操做服務器上了.
  2. 細節決定成敗,歷時三天兩夜,加油吧
  3. 總測試沒有很好的測出來效果,但也是沒什麼問題的,數據庫畢竟和網站服務器不同
  4. 腳本寫的很是敷衍
相關文章
相關標籤/搜索