您的位置:首页 > 运维架构 > 网站架构

如何构建Keepalived+HAProxy实现高可用,负载均衡,动静分离。

2014-08-06 23:02 633 查看

一、HAProxy简介


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

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

                                                                                                                                                                        ————百度百科

 

HAProxy负载均衡的调度算法:

roundrobin:动态调度算法,根据权重进行轮叫类似(wrr),并且权重可以在运行时进行调整,支持慢速启动。

static-rr:静态调度算法,轮叫方式,没有动态算法的特殊功能。

leastconn:最少连接调度算法类似(wlc),适用于给长连接应用做调度如MySQL,SSH。不适用于web场景。

source:同一个IP定向到同一个后端服务器,类似(sh)。可以通过hash-type 来定义类型,map-based(静态)consistent(动态)。

uri:对于同一个uri的请求到同一个后端服务器。(适用于调度缓存服务器)

url:根据url中的参数进行调度,可以根据来自同一个用户信息的请求,发往同一台后端服务器。

hdr:根据用户请求的首部进行调度。


接下来我们部署下面的环境:


nginx+php和MySQL这些后端服务器配置前面文章都有讲到这里省略


安装haproxy

yum install haproxy -y

编辑配置文件:vim  /etc/haproxy/haproxy.cfg

#---------------------------------------------------------------------

# Example configuration for a possible web application.  See the

# full configuration options online.

#

#   http://cbonte.github.io/haproxy-dconv

#

#---------------------------------------------------------------------


#---------------------------------------------------------------------

# Global settings

#---------------------------------------------------------------------

global

    # to have these messages end up in /var/log/haproxy.log you will

    # need to:

    #

    # 1) configure syslog to accept network log events.  This is done

    #    by adding the '-r' option to the SYSLOGD_OPTIONS in

    #    /etc/sysconfig/syslog

    #

    # 2) configure local2 events to go to the /var/log/haproxy.log

    #   file. A line like the following can be added to

    #   /etc/sysconfig/syslog

    #

    #    local2.*                       /var/log/haproxy.log

    #

    log         127.0.0.1 local2


    chroot      /var/lib/haproxy

    pidfile     /var/run/haproxy.pid

    maxconn     4000

    user        haproxy

    group       haproxy

    daemon


    # turn on stats unix socket

    stats socket /var/lib/haproxy/stats


#---------------------------------------------------------------------

# common defaults that all the 'listen' and 'backend' sections will

# use if not designated in their block

#---------------------------------------------------------------------

defaults

    mode                    http  //设定默认运行模式

    log                     global

    option                  httplog  //启用http请求日志。

    option                  dontlognull //不记录空信息

    option http-server-close  //开启服务器端关闭,支持客户端一侧的长连接。

    option forwardfor       except 127.0.0.0/8 //在转发请求的时候,给请求报文添加一个首部信息,忽略本机。

    option                  redispatch   //请求重新分发

    retries                 3  //向后端服务器发出请求失败后,重试的次数。

    timeout http-request    10s  //请求的超时时间

    timeout queue           1m  //在请求等待队列中的超时时间

    timeout connect         10s  //paproxy连接后端服务器的超时时间

    timeout client          1m   //客户端非活动长连接的超时时间

    timeout server          1m   //服务器端非活动长连接的超时时间

    timeout http-keep-alive 10s

    timeout check           10s   //健康状态检测超时时间

    maxconn                 5000  //设定每个进程所响应的最大连接数


#---------------------------------------------------------------------

# main frontend which proxys to the backends

#---------------------------------------------------------------------

listen stats

  mode http

  bind *:9999  //设置侦听的端口

  stats enable  //启用stats

  stats hide-version  //隐藏程序的版本号

  stats uri  /administrator/login  // 指定url

  stats realm  HAProxy\ stats messages  //认证的提示标题信息

  stats auth  admin:admin  //定义登录stats帐号和密码。

  stats admin if TRUE  //启用管理功能,必须通过认证才允许登录管理

frontend  main

        bind *:80

    acl url_static       path_beg       -i /static /images /javascript /stylesheets

    acl url_static       path_end       -i .jpg .gif .png .css .js .bmp .ico .txt .html

    use_backend static          if url_static

    default_backend             dynamic    //定义默认代理的后端服务器群


#---------------------------------------------------------------------

# static backend for serving up images, stylesheets and such

#---------------------------------------------------------------------

backend static  定义静态请求响应服务器群

    balance     roundrobin  //定义负载均衡算法

    server      static1 172.16.1.110:80 check maxconn 6000


#---------------------------------------------------------------------

# round robin balancing between the various backends

#---------------------------------------------------------------------

backend dynamic  定义动态请求响应服务器群

    balance     roundrobin

    server   sport1 172.16.1.100:80 check inter 2 rise 1 fall 3 maxconn 2000

    server   sport2 172.16.1.101:80 check inter 2 rise 1 fall 3 maxconn 2000


配置haproxy日志

编辑/etc/sysconfig/rsyslog

SYSLOGD_OPTIONS="-c 2 -r "

定义日志设备

vim /etc/rsyslog.conf

local2.*                 /var/log/haproxy.log


然后安装keepalived,编辑配置文件 vim /etc/keepalived/keepalived.conf


! Configuration File for keepalived


global_defs {

   notification_email {

  root@localhost

   }

   notification_email_from keepalived@localhost

   smtp_server 127.0.0.1

   smtp_connect_timeout 30

   router_id LVS_DEVEL

}

vrrp_script chk_haproxy {

        script /etc/keepalived/server.sh  //自定义脚本,用于维护haproxy进程。

        interval 1

        weight 3

}


vrrp_instance VI_1 {

    state BACKUP

    interface eth0

    virtual_router_id 51

    priority 99

    advert_int 1

    authentication {

        auth_type PASS

        auth_pass a0f12bf066bb9605

    }

    virtual_ipaddress {

        192.168.18.254/24 dev eth0 label eth0:0

    }

        trac 24000 k_script {

        chk_haproxy

}

        notify_master "/etc/keepalived/notify.sh master"   //自定义脚本,用于监控状态发生转变。

        notify_backup "/etc/keepalived/notify.sh backup"

        notify_fault "/etc/keepalived/notify.sh fault"

}


server.sh,这个脚本功能是检测,haproxy进程是否存在,如果不存在则重启haproxy服务。

如果当前主机启动不了haproxy服务时,则返回一个错误状态码,降低优先级,使得节点资源迁移。

#!/bin/bash

#

pidof haproxy &>/dev/null

RETVL=$?

if [ "$RETVL" -eq 0 ];then

        exit 0;

else

        /etc/init.d/haproxy restart

pidof haproxy &>/dev/null

RETVL=$?

[ "$RETVL" -eq 0] && exit 0 || exit 5

fi


notify.sh,这个脚本功能是在主备状态发生转换时发送邮件通知管理员,并且启动haproxy服务。

#!/bin/bash

#description: An example of notify script

vip=192.168.18.254

contact='root@localhost'


notify() {

    mailsubject="`hostname` to be $1: $vip floating"

    mailbody="`date '+%F %H:%M:%S'`: vrrp transition, `hostname` changed to be $1"

    echo $mailbody | mail -s "$mailsubject" $contact

}


case "$1" in

    master)

        notify master

        /etc/rc.d/init.d/haproxy start

        exit 0

    ;;

    backup)

        notify backup

        /etc/rc.d/init.d/haproxy stop

        exit 0

    ;;

    fault)

        notify fault

        /etc/rc.d/init.d/haproxy stop

        exit 0

    ;;

    *)

        echo 'Usage: `basename $0` {master|backup|fault}'

        exit 1

    ;;

esac


haproxy配置两个节点一样。

keepalived备节点和主节点差不多,只需要改动初始状态为BACKUP降低优先级即可,将脚本文件也要一并同步过去。

配置完成以后,启动两边的keepalived即可。


笔者启用了6台虚拟机完成了,测试也基本成功,就不上图了。


欢迎大家与我交流QQ:1183710107








阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: