HAProxy提供高可用性、负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。HAProxy特别适用于那些负载特大的web站点,这些站点通常又需要会话保持或七层处理。HAProxy运行在时下的硬件上,完全可以支持数以万计的并发连接。并且它的运行模式使得它可以很简单安全的整合进您当前的架构中, 同时可以保护你的web服务器不被暴露到网络上。

HAProxy实现了一种事件驱动、单一进程模型,此模型支持非常大的并发连接数。多进程或多线程模型受内存限制 、系统调度器限制以及无处不在的锁限制,很少能处理数千并发连接。事件驱动模型因为在有更好的资源和时间管理的用户端(User-Space) 实现所有这些任务,所以没有这些问题。此模型的弊端是,在多核系统上,这些程序通常扩展性较差。这就是为什么他们必须进行优化以 使每个CPU时间片(Cycle)做更多的工作。

HAProxy的配置文件分为:global,defaults,frontend,backend四部分

9 #---------------------------------------------------------------------
 10 # Global settings
 11 #---------------------------------------------------------------------
 12 global
 13     # to have these messages end up in /var/log/haproxy.log you will
 14     # need to:
 15     #
 16     # 1) configure syslog to accept network log events.  This is done
 17     #    by adding the '-r' option to the SYSLOGD_OPTIONS in
 18     #    /etc/sysconfig/syslog
 19     #
 20     # 2) configure local2 events to go to the /var/log/haproxy.log
 21     #   file. A line like the following can be added to
 22     #   /etc/sysconfig/syslog
 23     #
 24     #    local2.*                       /var/log/haproxy.log
 25     #
 26     log         127.0.0.1 local2
 27 
 28     chroot      /var/lib/haproxy
 29     pidfile     /var/run/haproxy.pid
 30     maxconn     4000
 31     user        haproxy
 32     group       haproxy
 33     daemon
 34 
 35     # turn on stats unix socket
 36     stats socket /var/lib/haproxy/stats
 37 
 38 #---------------------------------------------------------------------
 39 # common defaults that all the 'listen' and 'backend' sections will
 40 # use if not designated in their block
 41 #---------------------------------------------------------------------
 42 defaults
 43     mode                    http
 44     log                     global
 45     option                  httplog
 46     option                  dontlognull
 47     option http-server-close
 48     option forwardfor       except 127.0.0.0/8
 49     option                  redispatch
 50     retries                 3
 51     timeout http-request    10s
 52     timeout queue           1m
 53     timeout connect         10s
 54     timeout client          1m
 55     timeout server          1m
 56     timeout http-keep-alive 10s
 57     timeout check           10s
 58     maxconn                 3000
 59 
 60 #---------------------------------------------------------------------
 61 # main frontend which proxys to the backends
 62 #---------------------------------------------------------------------
 63 frontend  main *:80
 64     default_backend            websrvs
 65 
 66 #---------------------------------------------------------------------
 67 # static backend for serving up images, stylesheets and such
 68 #---------------------------------------------------------------------
 69 backend websrvs
 70     balance     roundrobin
 71     server      web1 172.16.100.22:80 check
 72     server      web2 172.16.100.23:80 check

**HAProxy:
    http协议做反向代理
    tcp做负载均衡**

**做反向代理**

代理相关的配置可以如下配置段中。        配置分为两段:
            global
                配置参数:log, maxconn, ...
            proxies
                defaults, frontend, backend, listen
    示例:
frontend main *:80
            default_backend websrvs
        backend websrvs
            balance roundrobin
            server web1 172.16.100.68 check
            server web2 172.16.100.69 check

“`

重点内容
- defaults
- frontend
- backend
- listen

“defaults”段用于为所有其它配置段提供默认参数,这配置默认配置参数可由下一个“defaults”所重新设定。

“frontend”段用于定义一系列监听的套接字,这些套接字可接受客户端请求并与之建立连接。

“backend”段用于定义一系列“后端”服务器,代理将会将对应客户端的请求转发至这些服务器。

“listen”段通过关联“前端”和“后端”定义了一个完整的代理,通常只对TCP流量有用。

所有代理的名称只能使用大写字母、小写字母、数字、-(中线)、_(下划线)、.(点号)和:(冒号)。此外,ACL名称会区分字母大小写。`

代理参数:
负载均衡调度算法
balance:
指明调度算法;
动态:权重可动态调整
静态:调整权重不会实时生效

roundrobin: 轮询,动态算法,每个后端主机最多支持4128个连接;
        static-rr: 轮询,静态算法,每个后端主机支持的数量无上限;
        leastconn: 根据后端主机的负载数量进行调度;仅适用长连接的会话;动态;
        source:
            hash-type:
                map-based:取模法;静态;
                consistent:一致性哈希法;动态;
        uri:
            hash-type
                map-based:
                consistent:
        url_param: 根据url中的指定的参数的值进行调度;把值做hash计算,并除以总权重;
            hash-type
                map-based:
                consistent:
        hdr(<name>) :根据请求报文中指定的header(如use_agent, referer, hostname)进行调度;把指定的header的值做hash计算;
            hash-type
                map-based:
                consistent:

server:

server <name> <addr>[:port] [param*]
            backup: 设定当前server为backup server;
            check: 健康状态检测;
                inter <delay>:检测时间间隔;单位为ms, 默认为2000; 
                fall: up --> down, soft state, soft state, hard state; 
                rise:down --> up, 
            cookie <value>:
            maxconn: 此服务接受的并发连接的最大数量;
            maxqueue: 请求队列的最大长度;
            observe: 根据流量判断后端server的健康状态;
            weight: 指定权重,默认为1,最大为256;0表示不被调度;
            redir <prefix>: 重定向;所有发往此服务器的请求均以302响应;

后端http服务时的健康状态的检测方法:
option httpchk

基于浏览器cookie实现session sticky:
backend websrvs
balance roundrobin
cookie SERVERID insert nocache indirect
server web1 172.16.100.68:80 check weight 1 cookie websrv1
server web2 172.16.100.69:80 check weight 3 cookie websrv2

要点:
(1) 每个server有自己惟一的cookie标识;
(2) 在backend中定义为用户请求调度完成后操纵其cookie

启用stats:
        listen statistics 
            bind *:9090
            stats enable
            stats hide-version
            #stats scope .
            stats uri /haproxyadmin?stats
            stats realm "HAPorxy\ Statistics"
            stats auth admin:mageedu
            stats admin if TRUE

    向日志中记录额外信息:
        capture request header
        capture response header

    当mode为http时,记录丰富的日志信息:
        option httplog

    错误页面重定向:
        errorfile: 使用haproxy主机本地文件进行响应;
        errorloc, errorloc302: 使用指定的url进行响应,响应状态码为302;不适用于GET以外的其它请求方法;
        errorloc303:返回303状态码;

访问控制:
    http_request
    tcp_request

添加请求或响应报文首部:
    reqadd
    rspadd

动静分离的示例

frontend  main
            bind *:80
            bind *:8080
            acl url_static       path_beg       -i /static /images /javascript /stylesheets
            acl url_static       path_end       -i .jpg .gif .png .css .js

            use_backend static          if url_static
            default_backend             appsrvs

        #---------------------------------------------------------------------
        # static backend for serving up images, stylesheets and such
        #---------------------------------------------------------------------
        backend static
            balance roundrobin
            server static1 172.16.100.11 check
            server static2 172.16.100.12 check

        backend appsrvs
            balance     roundrobin
            option forwardfor except 127.0.0.1 header X-Client
            option httpchk
            cookie SERVERID insert indirect nocache
            server  web1 172.16.100.7:80 check cookie web1
            server  web2 172.16.100.8:80 check cookie web2