使用nginx进行负载均衡

nginx主要用于1:请求分流 2:负载均衡。用在大型系统(集群)上,在单机上体现不出优势。 
 
本实例在windows环境下进行。 
 
一、安装nginx 
 
1、下载nginx1.8.0版 
2、解压至1、下载nginx1.8.0版 
2、解压至c:\nginx-1.8.0 
3、在cmd控制台进入到c:\nginx-1.8.0目录 
4、运行start nginx启动 nginx服务器 
5、在浏览器中输入 localhost ,如果能打开nginx欢迎页面,说明启动成功。 
 
相关命令: 
nginx -s stop     quick exit 
nginx -s quit     graceful quit 
nginx -s reload     changing configuration, starting a new worker, quitting an old worker gracefully 
nginx -s reopen     reopening log files 
tasklist /fi "imagename eq nginx.exe" 查看启动的nginx进程 
3、在cmd控制台进入到c:\nginx-1.8.0目录 
4、运行start nginx启动 nginx服务器 
5、在浏览器中输入 localhost ,如果能打开nginx欢迎页面,说明启动成功。 
 
相关命令: 
nginx -s stop     quick exit 
nginx -s quit     graceful quit 
nginx -s reload     changing configuration, starting a new worker, quitting an old worker gracefully 
nginx -s reopen     reopening log files 
tasklist /fi "imagename eq nginx.exe" 查看启动的nginx进程 
 
二、部署项目 
 
基本思路 
 
    nginx用于处理静态页面和请求分流调度。 
 
    1、在nginx安装完毕后,在nginx.conf中配置D:\dev\nginx作为nginx的执行目录(机器ip:192.168.11.35):如下 
        server { 
            listen       localhost:8888; #8888为端口号 
            root         D:/dev/nginx/myspring;#myspring是项目名称 
            index         test.html; 
            #jsp动态页面由此proxy_pass处理 
            #location ~ \.jsp$ { 
            #    root   html; 
            #    index  index.html index.htm; 
            #    proxy_pass http://192.168.11.35:8080; 
            #} 
        } 
    打开静态页面:重启nginx服务器后,访问http://localhost:8888/test.html将显示test.html中的内容。 
     
    2、在windows中使用tomcat部署一份myspring项目,ip为192.168.11.35,端口号设为8080 
    3、在linux中使用tomcat部署一份myspring项目,ip为192.168.11.38,端口号为8181 
    4、配置负载均衡: 
        在http{}中配置 
        #负载均衡的两台机器 
        upstream myCluster { 
            server 192.168.11.35:8080; #1/6的请求将会被分配到此服务器 
            server 192.168.11.38:8181 weight=5; #权重 指5/6的请求将会被分配到此服务器 
        }  
        在server {}中配置 
        location ~ \.jsp$ { 
            proxy_pass http://myCluster ; #这里的名字和上面的cluster的名字相同 
            proxy_redirect off; 
            proxy_set_header Host $host; 
            proxy_set_header X-Real-IP $remote_addr; 
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 

             proxy_connect_timeout   1; #宕机时超时时间
             proxy_send_timeout      1;
             proxy_read_timeout      1;
        }  
        以上配置表示访问html静态页面时,由nginx自己处理。当访问jsp动态页面时,nginx根据设置的权重将请求分流到35,38两台服务器中处理,处理后结果返回到页面显示。 
        访问localhost:8888/myspring/default.jsp,将会随机分配给35或38的服务器处理。 
         
         
    说明:以上myspring是我使用的项目示例,项目直接路径下包含test.html和default.jsp两个文件。 
          nginx还有很多参数这里没有使用到,具体可上Nginx官网了解。

posted @ 2015-05-29 09:50  hejinsheng  阅读(313)  评论(0编辑  收藏  举报