haproxy给mysql做负载均衡

jopen 9年前

一、首先安装haproxy

wget http://haproxy.1wt.eu/download/1.4/src/haproxy-1.4.24.tar.gz
tar zcvf haproxy-1.4.24.tar.gz
cd haproxy-1.4.24
make TARGET=linux26 PREFIX=/usr/local/haproxy #将haproxy安装到/usr/local/haproxy
make install PREFIX=/usr/local/haproxy
#PREFIX必须用大写,否则无法安装到指定目录/usr/local/haproxy中
二、配置
在/usr/local/haproxy/etc/下新建haproxy.cfg配置文件。内容为:

global
        log 127.0.0.1   local0 info    #日志相关
        log 127.0.0.1   local1 notice
        maxconn 4096
        chroot /usr/local/haproxy
        uid root
        gid root
        daemon
        #debug
        #quiet
        pidfile /usr/local/haproxy/haproxy.pid
 
defaults
        log     global
        mode    http
        #option httplog
        option  dontlognull
        retries 3
        option redispatch
        maxconn         2000
        contimeout      5000
        clitimeout      50000
        srvtimeout      50000
 
listen  mysql
        bind 0.0.0.0:23306    #代理端口
        mode tcp              #模式 TCP
        option mysql-check user root   #mysql健康检查  root为mysql登录用户名
        balance roundrobin            #调度算法
        server mysql1 192.168.153.128:3306 weight 1 check  inter 1s rise 2 fall 2 #健康检查加上check
        server mysql2 192.168.153.134:3306 weight 1 check  inter 1s rise 2 fall 2
listen stats     #监控
           mode http
           bind 0.0.0.0:8888
           stats enable
           stats uri /dbs
           stats realm Global\ statistics
           stats auth admin:admin
</div>

#option mysql-check user root #mysql健康检查 root为mysql登录用户名 注释掉 

两个用户都要开启mysql服务
三、启动
[root@web2 etc]# /usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/etc/haproxy.cfg

[root@web2 etc]# cd ../sbin/

[root@web2 sbin]# ls

haproxy

[root@web2 sbin]# ps -ef | grep haproxy

root 4223 1 0 18:12 ? 00:00:00 /usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/etc/haproxy.cfg

root 4228 3754 0 18:12 pts/0 00:00:00 grep haproxy

[root@web2 sbin]# 
四、访问
ip:8888/dbs
输入admin admin登录