83
ngx_http_upstream_module 默認編譯進Nginx
Syntax: | upstream |
---|---|
Default: | — |
Context: | http |
代碼示列:
upstream test { server 116.196.123.9:8011 weight=2 max_conns=2 max_fails=2 fail_timeout=5; #權重配了2 server 116.196.123.9:8012 weight=1; #權重配了1 keepalive 32; } server { listen 80; server_name shop.com.cn location /{ proxy_pass http://test; proxy_http_version 1.1; #http 1.0不支持長鏈接 為了限制1.0請求 這里做了指定 proxy_set_header Connection ""; } }
上游服務器代碼示列:
server { listen 8011; default_type text/plain; return 200 '8011 server respons\n'; } server { listen 8012; default_type text/plain; return 200 '8012 server response\n'; }
然后在上游服務器上 啟動轉包看 下 >> tcpdump -vvv port 8011
二、用HASH算法實現負載均衡
首先 我們來看下 ip_hash指令
upstream test { ip_hash; #當這里添加了ip_hash weight權重將失效 server 192.168.0.49:8011 ; server 192.168.0.49:8012 ; keepalive 32; }
請求將根據用戶的IP地址負載均衡
訪問示列:curl -H 'X-Forwarded-For:116.196.123.9' http://116.196.115.53
hash指令 (hash指令不能和ip_hash指令同時使用)
upstream test { hash user_$arg_username;#自定義參數用 server 192.168.0.49:8011 ; server 192.168.0.49:8012 ; keepalive 32; }
請求將根據用戶的自定義username參數負載均衡
訪問示列: curl http://116.196.115.53?username=e12312