經過ip_hash作會話保持有必定的缺陷,這個是經過客戶端ip來實現。同一個網絡下衆多客戶端訪問服務器會被扔到同一臺機器,再或者是CDN也 會致使負載不均衡。因此要實現經過客戶端cookie實現,包括F五、深信服設備其中的會話保持也是經過插入cookie值來實現會話保持。下次客戶端訪 問服務器,帶上本地cookie,nginx中的sticky模塊分析並扔到對應服務器中。nginx
0 工做原理apache
軟件版本:瀏覽器
nginx-1.6.0
nginx-sticky-module-1.1服務器
1 下載 Session Stickycookie
2 安裝模塊網絡
[root@localhost nginx-1.6.0]# ./configure --prefix=/usr/local/nginx --with-pcre=/usr/local/pcre-8.35 --with-zlib=/usr/local/zlib-1.2.8 --with-http_ssl_module --with-openssl=/usr/local/openssl-1.0.1c --add-module=/usr/local/src/nginx-sticky-module-1.1 [root@localhost nginx-1.6.0]# make [root@localhost nginx-1.6.0]# make install
make時報錯:負載均衡
objs/addon/nginx-sticky-module-1.1/ngx_http_sticky_misc.o] 錯誤 1dom
參考解決方法:google
方法一:spa
nginx-1.5.x以上版本和nginx-sticky-module-1.1編譯會有點問題,應該是nginx新版本沒有相應的nginx- sticky-module,解決辦法是把nginx-sticky-module-1.1/ngx_http_sticky_misc.c的281行修 改成:
digest->len = ngx_sock_ntop(in,sizeof(struct sockaddr_in), digest->data, len, 1);
方法二:
下降nginx版本爲nginx-1.2.3編譯經過。
sticky模塊參數只用於upstream段中,而且不能和ip_hash同時存在。
支持的參數:
sticky [name=route] [domain=.foo.bar] [path=/] [expires=1h] [hash=index|md5|sha1] [no_fallback];
name: 能夠爲任何的string字符,默認是route
domain:哪些域名下可使用這個cookie
path:哪些路徑對啓用sticky,例如path/test,那麼只有test這個目錄纔會使用sticky作負載均衡
expires:cookie過時時間,默認瀏覽器關閉就過時,也就是會話方式。
no_fallbackup:若是設置了這個,cookie對應的服務器宕機了,那麼將會返回502(bad gateway 或者 proxy error),建議不啓用。
配置參考(反向代理部分略過):
upstream apache {
sticky name=srv_id expires=1h domain=.test.com path=/;
server 192.168.5.4 max_fails=3 fail_timeout=20s;
server 192.168.5.5 max_fails=3 fail_timeout=20s;
}
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 參考資料