首先来简单认识一下 HaProxy :一款提供高可用性、负载均衡以及基于TCP(第四层)和HTTP(第七层)应用的代理软件,支持虚拟主机,是免费、快速而且可靠的一种解决方案。HAProxy 的实现基于事件驱动、单一进程模型,相似 Node.js 的进程模型,可以支撑很是大的并发链接数. html
如下实验环境均为 CentOS7 平台。 还须要两个 MySQL 实例,端口分别为3311,3312.linux
1.首先从官网上下载稳定版本 haproxy-1.9.2.tar,经过 FTP 工具传至服务器.git
2.解压 haproxy-1.9.2.tar,并进入解压后的文件夹github
tar -xvf haproxy-1.9.2.tar && cd haproxy-1.9.2
复制代码
3.因为压缩出来的是 haproxy 的源文件,因此还须要经过本地编译安装redis
make TARGET=generic # 指定编译的目标平台为通用
make install
复制代码
安装完成以后目录下文件就多了一些关于 haProxy 的文件算法
直接使用指令 haproxy
就是检查 Haproxy 是否安装成功.shell
[root@izm5e2w1juq9po7368cfj1z haproxy-1.9.2]# haproxy
HA-Proxy version 1.9.2 2019/01/16 - https://haproxy.org/
Usage : haproxy [-f <cfgfile|cfgdir>]* [ -vdVD ] [ -n <maxconn> ] [ -N <maxpconn> ]
[ -p <pidfile> ] [ -m <max megs> ] [ -C <dir> ] [-- <cfgfile>*]
-v displays version ; -vv shows known build options.
-d enters debug mode ; -db only disables background mode.
-dM[<byte>] poisons memory with <byte> (defaults to 0x50)
-V enters verbose mode (disables quiet mode)
-D goes daemon ; -C changes to <dir> before loading files.
-W master-worker mode.
-q quiet mode : don't display messages
-c check mode : only check config files and exit
-n sets the maximum total # of connections (2000)
-m limits the usable amount of memory (in MB)
-N sets the default, per-proxy maximum # of connections (2000)
-L set local peer name (default to hostname)
-p writes pids of all children to this file
-dp disables poll() usage even when available
-dR disables SO_REUSEPORT usage
-dr ignores server address resolution failures
-dV disables SSL verify on servers side
-sf/-st [pid ]* finishes/terminates old pids.
-x <unix_socket> get listening sockets from a unix socket
-S <unix_socket>[,<bind options>...] new stats socket for the master
复制代码
4.为 HaProxy 添加配置文件,命名为 haproxy.confbash
global
daemon # 后台方式运行
nbproc 1
pidfile haproxy.pid
defaults
mode tcp #默认的模式mode { tcp|http|health },tcp是4层,http是7层,health只会返回OK
retries 2 #两次链接失败就认为是服务器不可用,也能够经过后面设置
option redispatch #当serverId对应的服务器挂掉后,强制定向到其余健康的服务器
option abortonclose #当服务器负载很高的时候,自动结束掉当前队列处理比较久的连接
maxconn 4096 #默认的最大链接数
timeout connect 5000ms #链接超时
timeout client 30000ms #客户端超时
timeout server 30000ms #服务器超时
#timeout check 2000 #=心跳检测超时
log 127.0.0.1 local0 err #[err warning info debug]
balance roundrobin # 采用轮询算法
################# 配置#################
listen delegate #这里是配置负载均衡,test1是名字,能够任意
bind 0.0.0.0:3306 #这里是监听的IP地址和端口,端口号能够在0-65535之间,要避免端口冲突
mode tcp #链接的协议,这里是tcp协议
#maxconn 4086
#log 127.0.0.1 local0 debug
server s1 localhost:3312 #负载的MySQL实例1
server s2 localhost:3311 #负载的MySQL实例2 能够有多个,往下排列即
复制代码
具体配置参数说明可参考 HaProxy 官网的配置案例服务器
HaProxy 负载算法 HaProxy 支持多种负载算法,能够经过在配置文件中 balance
指定.cookie
5.加载配置文件方式启动 HaProxy
haproxy -f conf/haproxy.conf
复制代码
为了检验 MySQL 的负载均衡是否生效,咱们能够简单地使用 MySQL 客户端工具来链接试下,首先在两个 MySQL 实例中各自新建一个不一样名字的库,端口为3311建立 salve, 端口为3312的建立 salve11.