nginx 負載均衡tomcat

努力學習,超越自我。html

nginx是一個高性能http和反向代理服務器,也是一個IMAP/POP3/SMTP服務器。特色是內存佔用少,併發能力強。nginx

 

1、搭建環境web

nginx安裝:https://my.oschina.net/wangzonghui/blog/1620790apache

nginx歷史版本地址:後端

http://nginx.org/download/緩存

 

tomcat直接下載配置,解壓便可。tomcat

https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-7/v7.0.84/bin/apache-tomcat-7.0.84.tar.gz服務器

複製兩份tomcat,同一機器啓動兩個tomcat,修改其中一個請求端口爲8088和./webapp/ROOT/index.html文件,修改方式以下:網絡

 

2、負載均衡配置session

nginx有多種負載均衡模式:

一、輪詢(默認)
每一個請求按時間順序逐一分配到不一樣的後端服務器,若是後端服務器down掉,能自動剔除。
二、weight
指定輪詢概率,weight和訪問比率成正比,用於後端服務器性能不均的狀況。
二、ip_hash
每一個請求按訪問ip的hash結果分配,這樣每一個訪客固定訪問一個後端服務器,能夠解決session的問題。
三、fair(第三方)
按後端服務器的響應時間來分配請求,響應時間短的優先分配。
四、url_hash(第三方)
按訪問url的hash結果來分配請求,使每一個url定向到同一個後端服務器,後端服務器爲緩存時比較有效。

這裏走默認,修改nginx配置,路徑/usr/local/nginx/conf/nginx.conf

http中添加以下配置:

驗證腳本是否修改有誤,/user/local/nginx/sbin/nginx -t,

啓動 /user/local/nginx/sbin/nginx -s reload

如此,請求主機名或ip,重複刷新,能夠看到兩個tomcat切換。

 

3、線上配置實例

一個項目部署了兩個服務器,nginx每次接收請求後,輪詢(可選擇輪詢、最少鏈接、ip地址哈希、權重複制均衡)轉發不一樣地址的tomcat。

在http下增長upstream節點,choseapp是自定義的,根據須要指定。

    upstream choseapp {
      server localhost:8080;
      server localhost:8081;
    }

修改以前的location,將本來的ip和端口,換成choseap:

location /dw {
            proxy_pass http://choseapp/dw;
}

 

三、單個ip併發限制

首先http下增長以下內容:

imit_conn_zone $binary_remote_addr zone=one:10m;

$binary_remote_addr是nginx內部參數,zone定義配置名稱爲one,10M請求緩存大小

 

須要限制的location中增長:

    limit_conn one 1;  #這將指定一個地址只能同時存在一個鏈接。「one」與上面的對應,也能夠自定義命名
    limit_rate 300k;  #單個請求的網絡帶寬最大值

須要深度學習限制配置參照:http://www.javashuo.com/article/p-soasoqmd-ko.html

完整配置以下:

worker_processes  1; #啓動進程數

 #全局錯誤日誌及PID文件
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
    
    upstream choseapp {
      server localhost:8080;
      server localhost:8081;
    }
    limit_conn_zone $binary_remote_addr zone=one:10m;
    
    server {
        listen       8089;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }
        
        location /dw/ {
            limit_conn one 5;  #限制鏈接數
            #limit_rate 300k;  #每一個鏈接限速大小
            proxy_pass http://choseapp/dw/;
        }

        #error_page  404              /404.html;

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

}
相關文章
相關標籤/搜索