1、 工具
nginx-1.8.xhtml
apache-tomcat-6.xnginx
2、 目標
實現高性能負載均衡的Tomcat集羣:apache
![](http://static.javashuo.com/static/loading.gif)
3、 步驟
一、首先安裝好Nginx,上一篇文章已經詳細講述如何安裝Nginx,在這裏再也不詳細講述;瀏覽器
二、而後解壓兩個Tomcat(爲了後續能方便驗證nginx的轉發,採用了不一樣版本的tomcat),分別命名爲tomcat和tomcat-Second:tomcat
三、而後修改Tomcat的配置文件,第一臺Tomcat無需修改,對第二臺作以下修改分,打開Tomcat的conf目錄下的server.xml:服務器
共需修改3處端口:網絡
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
四、而後啓動兩個Tomcat,並訪問,看是否正常:(爲了後續能方便驗證nginx的轉發,採用了不一樣版本的tomcat)app
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
五、OK,如今咱們能夠開始配置Nginx來實現負載均衡了,其實很是的簡單,只須要配置好Nginx的/nginx/conf/nginx.conf配置文件便可:負載均衡
- worker_processes 1;#工做進程的個數,通常與計算機的cpu核數一致
-
- events {
- worker_connections 1024;#單個進程最大鏈接數(最大鏈接數=鏈接數*進程數)
- }
-
- http {
- include mime.types; #文件擴展名與文件類型映射表
- default_type application/octet-stream;#默認文件類型
-
- sendfile on;#開啓高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對於普通應用設爲 on,若是用來進行下載等應用磁盤IO重負載應用,可設置爲off,以平衡磁盤與網絡I/O處理速度,下降系統的負載。注意:若是圖片顯示不正常把這個改爲off。
-
- keepalive_timeout 65; #長鏈接超時時間,單位是秒
-
- gzip on;#啓用Gizp壓縮
-
- #服務器的集羣
- upstream netitcast.com { #服務器集羣名字
- server 127.0.0.1:8080 weight=1;#服務器配置 weight是權重的意思,權重越大,分配的機率越大。
- server 127.0.0.1:8081 weight=2;
- }
-
- #當前的Nginx的配置
- server {
- listen 80;#監聽80端口,能夠改爲其餘端口
- server_name localhost;############## 當前服務的域名
-
- location / {
- proxy_pass http://netitcast.com;
- proxy_redirect default;
- }
-
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- root html;
- }
- }
- }
核心配置以下:函數
![](http://static.javashuo.com/static/loading.gif)
到此配置完成,下面開始演示負載均衡。
六、首先,咱們啓動Nginx:
七、而後咱們便可輸入:localhost/examples/index.html查看運行情況了
第一次訪問,發現訪問的是Tomcat-Second上的程序:
![](http://static.javashuo.com/static/loading.gif)
而後刷新,訪問的仍是Tomcat上的程序:
![](http://static.javashuo.com/static/loading.gif)
接下來屢次F5刷新瀏覽器,發現頁面會在兩臺Tomcat上來回跳轉。