使用HAProxy路由MySQL讀請求
以下的例子使用HAProxy轉發請求到兩臺mysql從庫上。
Mysql:mysql 5.5
HAProxy IP: 172.28.10.192
Mysql Slave1:172.28.10.145
Mysql Slave2:172.28.10.150
在172.28.10.192上編譯和安裝haproxy
[root@cscscslocalhost 1109]# tar -zvfx haproxy-1.4.21.tar.gz
[root@cscscslocalhost haproxy-1.4.21]#make TARGET=linux26 PERFIX=/usr/local/haproxy
[root@cscscslocalhost haproxy-1.4.21]# make install PREFIX=/usr/local/haproxy
install -d /usr/local/haproxy/sbin
install haproxy /usr/local/haproxy/sbin
install -d /usr/local/haproxy/share/man/man1
install -m 644 doc/haproxy.1 /usr/local/haproxy/share/man/man1
install -d /usr/local/haproxy/doc/haproxy
for x in configuration architecture haproxy-en haproxy-fr; do \
install -m 644 doc/$x.txt /usr/local/haproxy/doc/haproxy ; \
--查看haproxy版本,如有返回表示安裝成功
[root@cscscslocalhost haproxy-1.4.21]# haproxy -v
HA-Proxy version 1.4.21 2012/05/21
Copyright 2000-2012 Willy Tarreau <w@1wt.eu>
[root@cscscslocalhost haproxy]# cd /usr/local/haproxy
--在haproxy安裝目錄中,新建conf和logs目錄
[root@cscscslocalhost haproxy]# mkdir conf
[root@cscscslocalhost haproxy]# mkdir logs
[root@cscscslocalhost haproxy]# ls
conf doc logs sbin share
--編寫haproxy的配置文件,在haproxy的軟件包中examples中有例子,可以復制過來再修改.
值得註意的有輪詢方式,轉發方式,每服務器的權重等信息。
[root@cscscslocalhost haproxy]# vi /etc/haproxy.cfg
global
log 127.0.0.1 local0
log 127.0.0.1 local1 notice
#log loghost local0 info
maxconn 4096
chroot /usr/share/haproxy
uid 99
gid 99
daemon
#debug
#quiet
defaults
log global
mode tcp
option httddplog
option dontlognull
retries 3
redispatch
maxconn 2000
contimeout 5000
clitimeout 50000
srvtimeout 50000
listen mysql_proxy
bind 0.0.0.0:23306
mode tcp
balance roundrobin
server db1 172.28.10.145:3307 check inter 2000 rise 2 fall 5 weight 1
server db2 172.28.10.150:3306 check inter 2000 rise 2 fall 5 weight 1
--新建對應的chroot目錄,否則會報錯,haproxy不能正常啟動
[root@cscscslocalhost haproxy]# haproxy -f /etc/haproxy.cfg
[ALERT] 314/142955 (12657) : [haproxy.main()] Cannot chroot(/usr/share/haproxy).
[root@cscscslocalhost haproxy]# mkdir /usr/share/haproxy
--啟動haproxy,查看端口,確保啟動成功.
[root@cscscslocalhost haproxy]# haproxy -f /etc/haproxy.cfg
[root@cscscslocalhost haproxy]# netstat -nltp | grep haproxy
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:23306 0.0.0.0:* LISTEN 12674/haproxy
--修改日誌的相關配置,讓haproxy能夠輸出日誌信息
[root@cscscslocalhost log]# vi /etc/syslog.conf
local6.* /var/log/haproxy.log
[root@cscscslocalhost haproxy]# vi /etc/sysconfig/syslog
SYSLOGD_OPTIONS=" -r -m 0"
[root@cscscslocalhost haproxy]# service syslog restart
Shutting down kernel logger: [ OK ]
Shutting down system logger: [ OK ]
Starting system logger: [ OK ]
Starting kernel logger: [ OK ]
--到此haproxy已經能夠正常的轉發mysql請求到後端的真正mysql服務器上了。