阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Nginx 基于cookie负载均衡

139次阅读
没有评论

共计 1786 个字符,预计需要花费 5 分钟才能阅读完成。

为什么要用 nginx 基于 cookie 的负责均衡而不使用 ip_hash 呢?

在多台服务器的情况下,为了确保一个客户只和一台服务器进行通信,我们势必使用长连接。使用什么方式来实现这种连接呢,常见的有使用 nginx 自带的 ip_hash 来做,我想这并不是一个好的办法,如果客户端前端是 CDN,或者说一个局域网的客户同时访问服务器,会出现服务端服务器负载分配不均衡,以及不能保证每次访问都粘滞在同一台服务器。如果基于 cookie 会是一种什么情形,想想看, 每台电脑都会有不同的 cookie,在保持长连接的同时还保证了服务器的压力均衡。

实施方法:
nginx-sticky 下载地址:

https://nginx-sticky-module.googlecode.com/files/nginx-sticky-module-1.1.tar.gz
因为 nginx 每次加入模块都需要重新编译才可以。

tar xvzf nginx-sticky-module-1.1.tar.gz
./configure …….. “–add-module=../nginx-sticky-module-1.1” \
在编译安装的时候如果服务器不安装 openssl-devel 的时候 make 的时候会报错误的
错误如下:
在包含自 /usr/local/src/ngx-tomcat/nginx-sticky-module-1.1/ngx_http_sticky_misc.c:11 的文件中

src/core/ngx_sha1.h:19:17: 错误:sha.h:没有那个文件或目录
In file included from /usr/local/src/ngx-tomcat/nginx-sticky-module-1.1/ngx_http_sticky_misc.c:11:
src/core/ngx_sha1.h:23: 错误:expected‘=’,‘,’,‘;’,‘asm’or‘__attribute__’before‘ngx_sha1_t’
/usr/local/src/ngx-tomcat/nginx-sticky-module-1.1/ngx_http_sticky_misc.c: 在函数‘ngx_http_sticky_misc_md5’中:
查看 src/core/ngx_sha1.h 其中有如下内容
16 #if (NGX_HAVE_OPENSSL_SHA1_H)
17 #include <openssl/sha.h>
18 #else
19 #include <sha.h>
20 #endif
所以安装 openssl-devel
yum install -y openssl-devel
然后 make make install 不会报错。
然后配置 nginx 如下:

upstream _cc {
sticky name=al_sticky;
server 127.0.0.1:80 weight=10 max_fails=2 fail_timeout=30s;
server 127.0.0.1:82 weight=10 max_fails=2 fail_timeout=30s;
}

即可实现 nginx 的基于 cookie 的负载均衡。
重启 nginx
/etc/init.d/nginx restart

相关阅读

Nginx 实现反向代理和负载均衡的配置及优化 http://www.linuxidc.com/Linux/2013-11/92909.htm

Nginx 做负载均衡报:nginx: [emerg] could not build the types_hash  http://www.linuxidc.com/Linux/2013-10/92063.htm

Nginx 负载均衡模块 ngx_http_upstream_module 详述 http://www.linuxidc.com/Linux/2013-10/91907.htm

Nginx+Firebug 让浏览器告诉你负载均衡将请求分到了哪台服务器  http://www.linuxidc.com/Linux/2013-10/91824.htm

Ubuntu 安装 Nginx php5-fpm MySQL(LNMP 环境搭建) http://www.linuxidc.com/Linux/2012-10/72458.htm

Nginx 的详细介绍:请点这里
Nginx 的下载地址:请点这里

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-01-20发表,共计1786字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中