nginx-sticky-module模块是nginx实现负载均衡的一种方案,和ip_hash负载均衡算法会有区别的
- ip_hash 根据客户端ip将请求分配到不同的服务器上.
- sticky 根据服务器个客户端的cookie,客户端再次请求是会带上此cookie,nginx会把有次cookie的请求转发到颁发cookie的服务器上.
安装Sticky
1. 下载sticky
# 创建目录
mkdir /usr/local/nginx/module
cd /usr/local/nginx/module
#下载sticky
wget https://bitbucket.org/nginx-goodies/nginx-sticky-module-ng/get/master.tar.gz
tar xf master.tar.gz
#解压
tar -zxvf master.tar.gz
2. 编译nginx
# 进入nginx安装目录
cd /usr/local/nginx-1.9.9
./configure --prefix=/usr/local/nginx-1.9.9 \
--sbin-path=/usr/local/nginx/sbin/nginx \
--conf-path=/usr/local/nginx/conf/nginx.conf \
--pid-path=/usr/local/nginx/run/nginx.pid \
--error-log-path=/usr/local/nginx/logs/error.log \
--http-log-path=/usr/local/nginx/logs/access.log \
--with-pcre \
--user=nginx \
--group=nginx \
--with-stream \
--with-threads \
--with-file-aio \
--with-http_v2_module \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--add-module=/usr/local/nginx/module/nginx-sticky-module #在此载入sticky模块
make
#更新检测
make upgrade
3. 查看模块是否被载入
cd /usr/local/nginx-1.9.9
./sbin/nginx -V
如下图表表示添加成功
4. 使用
upstream backend {
sticky name=ngx_cookie expires=6h;
server 192.168.31.240:8080 weight=3 max_fails=3 fail_timeout=10s;
server 192.168.31.241:8080 weight=3 max_fails=3 fail_timeout=10s;
server 192.168.31.242:8080 weight=6 max_fails=3 fail_timeout=10s;
server 192.168.31.243:8080;
server 192.168.31.244:8080 down;
}
name: cookie的名称
expire: 有效期
5. nginx 启动 停止 重启命令
/usr/local/nginx-1.9.9/sbin/nginx -s start
/usr/local/nginx1.9.9/sbin/nginx -s stop
/usr/local/nginx1.9.9/sbin/nginx -s reload