文章出處

apache、nginx之類的反向代理(轉發)功能,通常只能用于http協議,其它協議就不好使了(注:nginx據說商業版的,支持tcp協議了)。

haproxy可以彌補這方面的不足,haproxy支持http/tcp多種協議,可以當做rpc(thrift/gRPC/avro)框架前端的負載均衡轉發中間件,下面介紹基本使用:

以下環境均為mac OSX。

一、安裝

brew install haproxy 

默認安裝的是1.6.0版本,注:沒安裝 brew的,請先訪問http://brew.sh/ 安裝

安裝后的路徑為:

/usr/local/Cellar/haproxy/1.6.0

或者,也可以直接上官網http://www.haproxy.org/#down 下載

安裝完成后,輸入

haproxy -version 如果能看到類似下面的輸出:

HA-Proxy version 1.6.0 2015/10/13
Copyright 2000-2015 Willy Tarreau <willy@haproxy.org>

表示安裝成功

 

二、http轉發配置

隨便找個目錄(比如:~/work/cfg/),創建haproxy.cfg文件(文件名隨意),參考內容如下:

global
    daemon
    maxconn 256

defaults
    mode http
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

listen http-in
    bind *:9000
    server server1 127.0.0.1:8081 maxconn 32

主要是最后三行,表示將本機9000端口的http訪問,轉發到127.0.0.1:8081端口,即訪問: http://127.0.0.1:9000 相當于訪問http://127.0.0.1:8081

 

三、啟動

haproxy -f ~/work/cfg/haproxy.cfg -d 

正常的話,會輸出下面這些:

Available polling systems :
kqueue : pref=300, test result OK
poll : pref=200, test result OK
select : pref=150, test result OK
Total: 3 (3 usable), will use kqueue.
Using kqueue() as the polling mechanism.

 

此時,訪問http://localhost:9000/ 應該有結果 ,同時終端會有相關的信息輸出

注:如果啟動時,提示bind某端口失敗之類的,先檢查端口是否被占用

命令 lsof -i tcp:port  (port替換成端口號,比如9000)可以查看該端口被什么程序占用,并顯示pid,方便kill進程

如果端口也未占用,嘗試換成一個高一些的端口,我在mac本機嘗試時,剛開始使用80或81端口,始終起不來,用上述命令查端口占用,也沒被占用,換成一個高位端口后,才正常啟動,不知道是不是個別現象。

 

四、http負載均衡示例

global
    daemon
    maxconn 256

defaults
    mode http
    stats enable
    stats uri /haproxy-stats
    stats refresh 10s
    monitor-uri /haproxy-test
    balance roundrobin
    option httpclose
    option forwardfor
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms

listen my-web-cluster1
    bind *:9000
    server server1 127.0.0.1:80
    server server2 192.168.1.14:80

上面的配置表示,訪問http://localhost:9000/時,會轉發到127.0.0.1:80或192.168.1.14:80中的一臺

另外,訪問 http://localhost:9000/haproxy-stats 還能看到一個統計頁面, http://localhost:9000/haproxy-test 用于測試haproxy工作是否正常

 

五、tcp負載均衡配置示例

 1 global
 2     daemon
 3     nbproc 1
 4     pidfile /Users/yjmyzz/work/pid/haproxy.pid
 5 
 6 defaults
 7     mode tcp
 8     retries 3
 9     option redispatch
10     option abortonclose
11     maxconn 4096
12     timeout connect 5000ms
13     timeout client 30000ms
14     timeout server 30000ms
15     log 127.0.0.1 local0 notice err
16 
17 listen thrift-cluster
18     bind *:33210
19     mode tcp
20     balance roundrobin
21     server server1 localhost:33208
22     server server2 localhost:33209

注意下:8,9這二行,這表示如果某個節點掛了,重試3次以后,會轉發到其它節點,即單點故障遷移

 

參考文章:

http://cbonte.github.io/haproxy-dconv/configuration-1.6.html


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()