nginx upstream 一致性哈希模块
ngx_http_upstream_consistent_hash 模块是一个负载均衡器,使用一个内部一致性hash算法来选择合适的后端节点。与PHP的memcache模块memcache.hash_strategy兼容,这意味着可以使用php-memcache模块将内容存储到memcached集群中,而后通过nginx在集群中找到值。
该模块通过使用客户端信息(如:$ip, $uri, $args等变量)作为参数,使用一致性hash算法将客户端映射到后端节点。
该模块可以根据配置参数采取不同的方式将请求均匀映射到后端机器,比如:
- consistent_hash $remote_addr:可以根据客户端ip映射
- consistent_hash $request_uri: 根据客户端请求的uri映射
- consistent_hash $args:根据客户端携带的参数进行映射
指令
语法:consistent_hash variable_name
默认值:none
上下文:upstream
配置upstream采用一致性hash作为负载均衡算法,并使用配置的变量名作为hash输入。
安装
1
2
3
4
5
|
# wget https://github.com/replay/ngx_http_consistent_hash/archive/master.zip
# unzip master.zip
# ./configure --add-module=./3thparty/ngx_http_consistent_hash-master
# make
# make install
|
例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
upstream
somestream
{
consistent
_hash
$
request_uri
;
server
10.50.1.3
:
11211
;
server
10.50.1.4
:
11211
;
server
10.50.1.5
:
11211
;
}
.
.
.
server
{
listen
80
;
server_name
localhost
;
location
/
{
default_type
text
/
html
;
set
$
memcached
_key
$
request_uri
;
memcached_pass
somestream
;
error
_page
500
404
405
=
@
fallback
;
}
location
@
fallback
{
root
/
srv
/
www
/
whatever
;
fastcgi_intercept_errors
on
;
error
_page
404
=
@
404
;
set
$
script
$
uri
;
set
$
path
_info
""
;
include
/
usr
/
local
/
nginx
/
conf
/
fastcgi_params
;
fastcgi_param
SCRIPT_FILENAME
/
srv
/
www
/
whatever
/
test
.
php
;
fastcgi_param
SCRIPT
_NAME
$
script
;
fastcgi_param
REQUEST
_URI
$
uri
;
fastcgi
_pass
127.0.0.1
:
9000
;
}
}
|
参考文档:
http://wiki.nginx.org/HttpUpstreamConsistentHash
http://tengine.taobao.org/document_cn/http_upstream_consistent_hash_cn.html
收 藏
成长的对话版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!