结构
| ----> Server1
client ----> HAproxy -----> |
| ----> Server2
HAProxy 是七层代理,在使用 HAProxy 后,在 MySQL 上看不到 Apps 的源 IP 地址,看到的是 HAProxy 地址,而 MySQL 的权限访问设置是和 IP 地址有关,这样就导致了 MySQL 无法针对应用进行区分权限了,所以使用的时候要注意。
安装
# yum install haproxy
配置
# cat /etc/haproxy/haproxy.cfg
# 全局配置参数
global
log 127.0.0.1 local0 notice
user haproxy
group haproxy
# 一些默认参数
defaults
log global
retries 3
option dontlognull
option redispatch
maxconn 2000
timeout connect 3000
timeout server 5000
timeout client 5000
# 这个是我们定义的负载均衡的配置
listen mysql-lb1
# 绑定的IP和端口
bind 172.18.14.68:3306
# 模式是TCP
mode tcp
# 负载均衡算法是轮询
balance roundrobin
# 下面两个就是后端被访问的server
server mysql_1 172.18.14.71:3306 weight 1 check
server mysql_2 172.18.14.72:3306 weight 1 check
# 自带的监控服务器的配置
listen stats *:8888
# 监控模式是http
mode http
option httpclose
balance roundrobin
stats uri /
stats realm Haproxy\ Statistics
# 监控的用户名和密码
stats auth myadmin:myadmin
HAProxy测试
# mysql -h 172.18.14.68 -e "select @@hostname;"
多次执行可以看到轮询效果。