Nginx+Tomcat在Windows下做负载均衡

一、 为什么需要对Tomcat服务器做负载均衡

      Tomcat服务器作为一个Web服务器,其并发数在300-500之间,如果有超过500的并发数便会出现Tomcat不能响应新的请求的情况,严重影响网站的运行。另外,在访问量大的情况下,Tomcat的线程数会不断增加。由于Tomcat自身对内存的占用有控制,当对内存的占用达到最大值时便会出现内存溢出,对网站的访问严重超时等现象,这时便需要重新启动Tomcat以释放占用的内存,这样做便会阻断网站运行。

所以对Tomcat做负载均衡便很有必要。目前可以和Tomcat做负载均衡的主流服务器是Apache,但是Nginx由于功能多、配置简单等优点逐渐成为很多负载均衡服务器的首选。Nginx的并发数可达到50000,所以理论上可以和Tomcat以1:100的比例来配置,这样便可以很好的解决网站并发瓶颈问题。

二、 Nginx+Tomcat在Windows下负载均衡配置方法

       Nginx+Tomcat在Windows下做负载均衡相对在Linux下简单不少,因为不论是Nginx还是Tomcat只需要下载Windows下的安装包解压到某个目录下,然后就可以做配置了。

我选择的Nginx是nginx-0.8.49这个版本,Tomcat选择的是apache-tomcat-6.0.26。

下面就是配置过程:

1.将nginx-0.8.49.rar压缩包直接解压到某个目录下(如D:/负载均衡/nginx)。

2.将apache-tomcat-6.0.26.rar压缩包解压,因为是做负载均衡,所以至少要解压两个。(如分别解压到D:/负载均衡/tomcat_1和D:/负载均衡/tomcat_2下面)。

3.将要发布的项目发布到两个Tomcat根目录下的webapps下,保证两个Tomcat下面的项目名称相同。

4.修改其中一个Tomcat的配置文件,该配置文件位于Tomcat目录下的/conf/下,文件名为server.xml,修改其中的<Server port="8005" shutdown="SHUTDOWN">为<Server port="8006" shutdown="SHUTDOWN">,修改其中的

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />  

<Connector port="8088" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />  

修改后的文件如下:

  1 <?xml version='1.0' encoding='utf-8'?>
  2 
  3 <!--
  4 
  5   Licensed to the Apache Software Foundation (ASF) under one or more
  6 
  7   contributor license agreements.  See the NOTICE file distributed with
  8 
  9   this work for additional information regarding copyright ownership.
 10 
 11   The ASF licenses this file to You under the Apache License, Version 2.0
 12 
 13   (the "License"); you may not use this file except in compliance with
 14 
 15   the License.  You may obtain a copy of the License at
 16 
 17       http://www.apache.org/licenses/LICENSE-2.0
 18 
 19   Unless required by applicable law or agreed to in writing, software
 20 
 21   distributed under the License is distributed on an "AS IS" BASIS,
 22 
 23   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 24 
 25   See the License for the specific language governing permissions and
 26 
 27   limitations under the License.
 28 
 29 -->
 30 
 31 <!-- Note:  A "Server" is not itself a "Container", so you may not
 32 
 33      define subcomponents such as "Valves" at this level.
 34 
 35      Documentation at /docs/config/server.html
 36 
 37 -->
 38 
 39 <Server port="8006" shutdown="SHUTDOWN">
 40 
 41   <!--APR library loader. Documentation at /docs/apr.html -->
 42 
 43   <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
 44 
 45   <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
 46 
 47   <Listener className="org.apache.catalina.core.JasperListener" />
 48 
 49   <!-- Prevent memory leaks due to use of particular java/javax APIs-->
 50 
 51   <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
 52 
 53   <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
 54 
 55   <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
 56 
 57   <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
 58 
 59   <!-- Global JNDI resources
 60 
 61        Documentation at /docs/jndi-resources-howto.html
 62 
 63   -->
 64 
 65   <GlobalNamingResources>
 66 
 67     <!-- Editable user database that can also be used by
 68 
 69          UserDatabaseRealm to authenticate users
 70 
 71     -->
 72 
 73     <Resource name="UserDatabase" auth="Container"
 74 
 75               type="org.apache.catalina.UserDatabase"
 76 
 77               description="User database that can be updated and saved"
 78 
 79               factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
 80 
 81               pathname="conf/tomcat-users.xml" />
 82 
 83   </GlobalNamingResources>
 84 
 85   <!-- A "Service" is a collection of one or more "Connectors" that share
 86 
 87        a single "Container" Note:  A "Service" is not itself a "Container",
 88 
 89        so you may not define subcomponents such as "Valves" at this level.
 90 
 91        Documentation at /docs/config/service.html
 92 
 93    -->
 94 
 95   <Service name="Catalina">
 96 
 97     <!--The connectors can use a shared executor, you can define one or more named thread pools-->
 98 
 99     <!--
100 
101     <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
102 
103         maxThreads="150" minSpareThreads="4"/>
104 
105     -->
106 
107     <!-- A "Connector" represents an endpoint by which requests are received
108 
109          and responses are returned. Documentation at :
110 
111          Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
112 
113          Java AJP  Connector: /docs/config/ajp.html
114 
115          APR (HTTP/AJP) Connector: /docs/apr.html
116 
117          Define a non-SSL HTTP/1.1 Connector on port 8080
118 
119     -->
120 
121     <Connector port="8088" protocol="HTTP/1.1"
122 
123                connectionTimeout="20000"
124 
125                redirectPort="8443" />
126 
127     <!-- A "Connector" using the shared thread pool-->
128 
129     <!--
130 
131     <Connector executor="tomcatThreadPool"
132 
133                port="8080" protocol="HTTP/1.1"
134 
135                connectionTimeout="20000"
136 
137                redirectPort="8443" />
138 
139     -->          
140 
141     <!-- Define a SSL HTTP/1.1 Connector on port 8443
142 
143          This connector uses the JSSE configuration, when using APR, the
144 
145          connector should be using the OpenSSL style configuration
146 
147          described in the APR documentation -->
148 
149     <!--
150 
151     <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
152 
153                maxThreads="150" scheme="https" secure="true"
154 
155                clientAuth="false" sslProtocol="TLS" />
156 
157     -->
158 
159     <!-- Define an AJP 1.3 Connector on port 8009 -->
160 
161     <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
162 
163     <!-- An Engine represents the entry point (within Catalina) that processes
164 
165          every request.  The Engine implementation for Tomcat stand alone
166 
167          analyzes the HTTP headers included with the request, and passes them
168 
169          on to the appropriate Host (virtual host).
170 
171          Documentation at /docs/config/engine.html -->
172 
173     <!-- You should set jvmRoute to support load-balancing via AJP ie :
174 
175     <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">        
176 
177     -->
178 
179     <Engine name="Catalina" defaultHost="localhost">
180 
181       <!--For clustering, please take a look at documentation at:
182 
183           /docs/cluster-howto.html  (simple how to)
184 
185           /docs/config/cluster.html (reference documentation) -->
186 
187       <!--
188 
189       <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
190 
191       -->       
192 
193       <!-- The request dumper valve dumps useful debugging information about
194 
195            the request and response data received and sent by Tomcat.
196 
197            Documentation at: /docs/config/valve.html -->
198 
199       <!--
200 
201       <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
202 
203       -->
204 
205       <!-- This Realm uses the UserDatabase configured in the global JNDI
206 
207            resources under the key "UserDatabase".  Any edits
208 
209            that are performed against this UserDatabase are immediately
210 
211            available for use by the Realm.  -->
212 
213       <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
214 
215              resourceName="UserDatabase"/>
216 
217       <!-- Define the default virtual host
218 
219            Note: XML Schema validation will not work with Xerces 2.2.
220 
221        -->
222 
223       <Host name="localhost"  appBase="webapps"
224 
225             unpackWARs="true" autoDeploy="true"
226 
227             xmlValidation="false" xmlNamespaceAware="false">
228 
229         <!-- SingleSignOn valve, share authentication between web applications
230 
231              Documentation at: /docs/config/valve.html -->
232 
233         <!--
234 
235         <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
236 
237         -->
238 
239         <!-- Access log processes all example.
240 
241              Documentation at: /docs/config/valve.html -->
242 
243         <!--
244 
245         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" 
246 
247                prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
248 
249         -->
250 
251       </Host>
252 
253     </Engine>
254 
255   </Service>
256 
257 </Server>
View Code

5.修改Nginx配置文件nginx.conf,该文件位于Nginx根目录下的/conf下面。

① 在#gzip  on;后面加入下面配置:

upstream backend {
server localhost:8080;
server localhost:8088;
ip_hash;
}  

其中server localhost:8080为第一个Tomcat的启动地址,server localhost:8088为第二个Tomcat的启动地址,ip_hash用于做session同步。

② 修改第一个server{}配置中的listen  80;改为新的端口号,因为我的本机80端口被IIS占用,因此将此处改为listen 800;。并将

location / {
            root   html;
            index  index.html index.htm;
        }
改为:
location / {
            root   html;
            index  index.html index.htm;
proxy_pass                  http://backend;  
           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;
           client_max_body_size        10m;
           client_body_buffer_size     128k;
           proxy_connect_timeout       90;
           proxy_send_timeout          90;
           proxy_read_timeout          90;
           proxy_buffer_size           4k;
           proxy_buffers               4 32k;
           proxy_busy_buffers_size     64k;
           proxy_temp_file_write_size  64k;
        }  

其中proxy_pass参数和upstream backend{}对应。

经过上面这些步骤,负载均衡配置就完成,下面前分别启动两台tomcat,然后双击nginx根目录下的nginx.exe文件或者用start nginx启动nginx,打开浏览器,输入地址:http://localhost:800便可看到下面画面:

wpsD403.tmp

这说明已经成功跳转到Tomcat上面。下面以来电秀具体项目为例,输入地址:http://localhost:800/ldxwebpersonal/personal/index/index.action便可看到下面来电秀首页画面:

wpsD404.tmp

我们再看看两个Tomcat下面的日志显示:

端口号为8080的显示:

wpsD414.tmp

端口号为8088的显示:

wpsD415.tmp

这说明两个tomcat已经实现负载均衡。

原文地址:https://www.cnblogs.com/ftl1012/p/9375460.html