0 工作原理
Session Sticky
模块在
upstream
返回响应后,向客户的浏览器写入
Cookie
,默认名为
route
,保存的内容是一个
md5
码。
之后,模块接收到客户浏览器的请求时,就根据
route
来决定将请求转发到
upstream
中哪台服务器上。
这是源码包中附带的流程图,将模块的处理流程描述的非常清晰:
1 下载 Session Sticky
wget https://nginx-sticky-module.googlecode.com/files/nginx-sticky-module-1.1.tar.gz
2 安装模块
如果
Nginx
之前已经安装了,可以通过
nginx -V
命令查看当时编译的参数。在参数后面追加安装
Session Sticky
模块的参数,
避免影响之前
Nginx
已有模块。
进入
nginx
源码目录,执行命令:
./configure … --add-module=/usr/local/src/nginx-sticky-module-1.1
make
make install
3 激活模块
在
upstream
块中添加
sticky;
即可激活
Session Sticky
模块。
upstream {
sticky;
server 127.0.0.1:9000;
server 127.0.0.1:9001;
server 127.0.0.1:9002;
}
4 可用选项
The "sticky" command can take several arguments to control its behaviour:
sticky [name=route] [domain=.foo.bar] [path=/] [expires=1h] [hash=index|md5|sha1] [no_fallback];
Configuration
|
Description
|
Parameters
|
Default Value
|
name
|
the name of the cookie used to track the persistant upstream srv
|
can be any string
|
"route"
|
domain
|
the domain in which the cookie will be valid
|
can be any string
|
nothing. Let the browser handle this.
|
path
|
the path in which the cookie will be valid
|
can be any path
|
nothing. Let the browser handle this.
|
expires
|
the validity duration of the cookie
|
must be a duration greater than one second
|
nothing. It's a session cookie
|
hash
|
the hash mechanism to encode upstream server. It cant' be used with hmac
|
md5|sha1
|
md5
|
hmac
|
The HMAC hash mechanism to encode upstream server. It's like the hash mechanism but it uses hmac_key to secure the hashing. It can't be used with hash.
|
md5|sha1
|
none
|
hmac_key
|
The key to use with hmac. It's mandatory when hmac is set.
|
can be any string
|
none
|
no_fallback
|
When this flag is set, nginx will return a 502 (Bad Gateway orProxy Error) if a request comes with a cookie and the corresponding backend is unavailable.
|
no arguments
|
none
|
参考资料
1
使用
nginx sticky
模块实现基于
cookie
的负载均衡
2
官方网站