[例子] nginx負載均衡搭建及測試


一、Nginx + Tomcat 負載均衡測試(負載均衡+部分靜態圖片處理)


環境說明:  nginx+tomcat @ubuntu
ok 首先你得有一個Ubuntu或者什么其他的linux.
安裝jdk  tomcat  nginx 等.. 記得配置環境變量
本測試環境的配置如下:
jdk              /usr/java/jdk1.7
Nginx         /usr/nginx-1.4.2
redis           /usr/redis3.2.5-1
tomcat       /usr/apache/tomcat-7-1
                 /usr/apache/tomcat-7-2
                 /usr/apache/tomcat-7-3

1配置tomcat

Linux系統下怎樣配置多個Tomcat同時運行呢:

如何在同一系統里同時啟動多個Tomcat.
(1)配置環境變量vi /etc/profile
在最后加上配置, 比如這里加了3台tomcat 
#--------------------------------------------------------------------
#set tomcat path @olddoor
###  first tomcat  ###
CATALINA_BASE=/usr/apache/tomcat-7-1
CATALINA_HOME=/usr/apache/tomcat-7-1
TOMCAT_HOME=/usr/apache/tomcat-7-1
export CATALINA_BASE CATALINA_HOME TOMCAT_HOME

###  second tomcat ###
CATALINA_2_BASE=/usr/apache/tomcat-7-2
CATALINA_2_HOME=/usr/apache/tomcat-7-2
TOMCAT_2_HOME=/usr/apache/tomcat_7-2
export CATALINA_2_BASE CATALINA_2_HOME TOMCAT_2_HOME

### third tomcat ###
CATALINA_3_BASE=/usr/apache/tomcat-7-3
CATALINA_3_HOME=/usr/apache/tomcat-7-3
TOMCAT_HOME=/usr/apache/tomcat-7-3
export CATALINA_3_BASE CATALINA_3_HOME TOMCAT_3_HOME

#set java path--------------------------------------------------------
JAVA_HOME=/usr/java/jdk1.7
export JRE_HOME=$JAVA_HOME/jre
export CLASSPATH=$JAVA_HOME/lib:$JRE_HOME/lib:$CLASSPATH
export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH
(2) 3台tomcat的端口號記得在server.xml修改.
(3) 然后修改tomcat的bin目錄下的 catalina.sh, 加入代碼
以tomcat2為例
   export JAVA_HOME=
  export PATH=
  export CLASSPATH=
  ###以上三個環境變量就是JAVA的環境變量可以不寫###
  export CATALINA_BASE=$CATALINA_2_BASE  #配置對應的tomcat變量即可
  export CATALINA_HOME=$CATALINA_2_HOME
搞定. 啟動3個tomcat試一下效果.
默認訪問的tomcat-1的index.jsp如下
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
hello<br/>
<img id="img1" src=/test/static/404-1.jpg />
<img id="img1" src=/test/jpgs/123.jpg />
</body>
</html>
tomcat-2 和 tomcat-3的index.jsp 中的404圖片名字分別為404-2.jsp 和404-3.jpg
最后訪問效果
tomcat-1:
 
tomcat-2
 
tomcat3
tomcat2和tomcat3的webapps目錄下並未放置 jpgs/123.jpg圖片所以找不到.

2配置nginx

修改nginx.conf
#user  nobody;  # user  root root #Nginx所在的用戶和用戶組
user  root root; #Nginx所在的用戶和用戶組
worker_processes  1;# 啟動的工作進程數量
#錯誤日志存放路徑  
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
error_log  logs/error.log  info;  #add by olddoor-----------

#pid        logs/nginx.pid;

#add by olddoor-----------

#add end------------------

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  0;
    keepalive_timeout  65;

    #gzip  on;
	#add by olddor---------------------
	upstream localhost { 
	#發到localhost上的請求,通過Nginx轉發到實際處理請求的服務器
           server 192.168.64.132:8080 weight=1;
           server 192.168.64.132:8081 weight=1;
		   server 192.168.64.132:8082 weight=1;
    }
	#add by olddor over----------------
    server {
        listen       8000;  #宿主機訪問虛擬機的80端口好像有點問題,建議不使用80端口
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
			proxy_connect_timeout   3; #add by olddoor  
			proxy_send_timeout      30; #add by olddoor 
			proxy_read_timeout      30; #add by olddoor 
            proxy_pass http://localhost;  #add by olddoor
            #root   html; #ignore by olddoor 	
            #index  index.html index.htm; #ignore by olddoor 	
        }
		location  /test/jpgs/ {
            alias /data/imgs/;
        }		
		
		#location /jpgs
		

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }




        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443;
    #    server_name  localhost;

    #    ssl                  on;
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_timeout  5m;

    #    ssl_protocols  SSLv2 SSLv3 TLSv1;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers   on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}
通過
 server 192.168.64.132:8080 weight=1;
 server 192.168.64.132:8081 weight=1;
 server 192.168.64.132:8082 weight=1;
的配置完成3台tomcat的輪詢負載均衡.
訪問時候使用  192.168.64.132:8000/test 取代 192.168.64.132:8080/test ,  192.168.64.132:8081/test ,  192.168.64.132:8082/test

3 使用nginx管理部分靜態數據

配置方式可以直接攔截指定路徑的 jpg之類的文件.
這里只攔截目錄
location  /test/jpgs/ {
            alias /data/imgs/;  #即攔截   /test/jpgs/請求->匹配物理路徑:     /data/imgs/
        }
注意alias 和root 的攔截邏輯略有不同.

在linux服務器上創建對應的文件夾並上傳圖片123.jpg

啟動三台tomcat以及Nginx服務器. 然后進行測試:

繼續通過 192.168.64.132:8080/test訪問可以看到效果是:
 
兩張圖片的來源都是tomcat-1
 
而訪問 192.168.64.132:8000/test 使用nginx服務則
隨機顯示第一張圖片. 而第二張123.jpg 則顯示的是nginx指定目錄的圖片而非tomcat上的圖片.
 
或者是
 

 
2張圖片來源都是nginx, 只是第一個是nginx到tomcat上獲取. 第二張圖片被攔截到/data/imgs上獲取.
 以404-2為例
 

 

4 性能測試對比

使用ab工具的壓力測試方法和結果, ab是針對apache的性能測試工具,可以只安裝ab工具。
ubuntu安裝ab
apt-get install apache2-utils
centos安裝ab
yum install httpd-tools
通過命令測試:
ab -kc 1000 -n 1000 http://192.168.64.132:8080/test/
這個指令會使用1000個並發,進行連接1000次測試tomcat-1
ab -kc 1000 -n 1000 http://192.168.64.132:80/test/
這個指令會使用1000個並發,進行連接1000次測試nginx
對比結果:
8080
#用於描述每個請求處理時間的分布情況,例如:50% 28 50%請求處理時間不超過28毫秒 (這里所指的處理時間是指:Time per request )
Percentage of the requests served within a certain time (ms)
  50%     28
  66%     32
  75%     34
  80%     35
  90%     53
  95%     62
  98%     65
  99%     66
 100%   1823 (longest request)
second表示當前測試的服務器每秒可以處理16.54個靜態html的請求事務,后面的mean表示平均。這個數值表示當前機器的整體性能,值越大越好。
Requests per second:    547.04 [#/sec] (mean)
Time per request:       1828.016 [ms] (mean)
Time per request:       1.828 [ms] (mean, across all concurrent requests)
Transfer rate:          76.93 [Kbytes/sec] received
80   nginx在小規模請求下響應速度慢於直接請求tomcat, 而處理能力 nginx明顯強於tomcat
Percentage of the requests served within a certain time (ms)
  50%    107
  66%    201
  75%    243
  80%    257
  90%    334
  95%    360
  98%   1116
  99%   1117
 100%   1118 (longest request)
second表示當前測試的服務器每秒可以處理16.54個靜態html的請求事務,后面的mean表示平均。這個數值表示當前機器的整體性能,值越大越好。
Requests per second:    873.38 [#/sec] (mean)
Time per request:       1144.983 [ms] (mean)
Time per request:       1.145 [ms] (mean, across all concurrent requests)
Transfer rate:          216.83 [Kbytes/sec] received

當請求改為1000個並發,進行連接1000次后
8080已經無法及時響應
This is ApacheBench, Version 2.3 <$Revision: 1528965 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking localhost (be patient)
Total of 9967 requests completed
而80還是穩穩的
Server Hostname:        localhost
Server Port:            80

Time taken for tests:   1.145 seconds
Complete requests:      1000
Failed requests:        551
   (Connect: 0, Receive: 0, Length: 551, Exceptions: 0)
Non-2xx responses:      1000
Keep-Alive requests:    0
Total transferred:      254220 bytes
HTML transferred:       105792 bytes
second表示當前測試的服務器每秒可以處理16.54個靜態html的請求事務,后面的mean表示平均。這個數值表示當前機器的整體性能,值越大越好。
Requests per second:    873.38 [#/sec] (mean)
Time per request:       1144.983 [ms] (mean)
Time per request:       1.145 [ms] (mean, across all concurrent requests)
Transfer rate:          216.83 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       16   26   4.6     27      33
Processing:    16  155 174.5     88    1101
Waiting:       13  155 174.6     88    1101
Total:         44  181 172.5    107    1118

Percentage of the requests served within a certain time (ms)
  50%    107
  66%    201
  75%    243
  80%    257
  90%    334
  95%    360
  98%   1116
  99%   1117
 100%   1118 (longest request)

tips 如需將屏幕上的測試結果生成為文本文件, 可以在測試時候配合|tee 命令
如:
ab -kc 1000 -n 1000 http://192.168.64.132:80/test/ |tee /usr/111.txt  #將結果保存到/usr/111.txt中



二、Nginx + Tomcat +Redis (用戶session會話集中管理)


在上例的基礎上新增Redis, 用於集中管理用戶會話session
效果如圖
 
配置過程
1 、實驗環境介紹

安裝nginx、tomcat、redis服務

軟件 version ip:port
Nginx 1.4.6 192.168.127.58 : 8000
Redis 3.2.5-1 192.168.127.58 : 7001
tomcat-7-1
7.0.73
192.168.127.58:8080
tomcat-7-2
7.0.73
192.168.127.58:8081
tomcat-7-3
7.0.73
192.168.127.58:8082

2、測試:
編寫id.jsp 放到3個tomcat的 /webapps/test下
<body>
 response from tomcat_3<br/>
<%=session.getId() %>
</body>
此時分別訪問192.168.127.58:8080/test/id.jsp   192.168.127.58:8081/test/id.jsp  192.168.127.58:8082/test/id.jsp   地址,因為訪問的是不同web服務器,所以各自顯示不同的頁面內容及session值肯定不同。

3、配置tomcat的session管理(持久化到redis中):
  • 添加jedis-2.0.0.jar、tomcat-redis-session-manager-1.2-tomcat-7-java-7、commons-pool-1.3.jar 三個jar到tomcat的lib目錄下;
            注意不可用commons-pool-1.2.jar
  • 修改tomcat的conf/context.xml 文件;
        
<!--配置對應redis的服務端口 並非后台端口-->
<Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
<Manager className="com.radiadesign.catalina.session.RedisSessionManager"
             host="localhost" 
             port="7001" 
             database="0" 
             maxInactiveInterval="60"  />
4  配置Nginx的負載均衡
本文第一部分已經做了。跳過

5、驗證:
訪問
的結果都是一樣的 session id
response from tomcat_1 
E47C459C5B9800294F408D0FFCFEFFD8

response from tomcat_2
E47C459C5B9800294F408D0FFCFEFFD8

response from tomcat_3
E47C459C5B9800294F408D0FFCFEFFD8
  • 使用 redis-cli 連接 redis 服務器,查看會顯示有 “E47C459C5B9800294F408D0FFCFEFFD8” key的 session 數據,value為序列化數據。

登錄redis-cli
 redis 查詢所有的key
keys *
 







 








免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM