win7+nginx+tomcat均衡負載配置

Win7+Nginx+Tomcat負載均衡配置

3臺機器模擬測試:192.168.101.23 配置nginx服務;192.168.101.222 配置tomcat1;192.168.101.5 配置tomcat2;

一、 下載Nginxnginx-1.5.8.zip)

下載地址:http//nginx.org/download/nginx-1.5.8.zip

解壓到D/serve目錄下

如圖1所示:


 

è 雙擊運行nginx.exe,屏幕一閃而過或者在DOS裏面敲打命令,如圖所示:\


 

可以看到屏幕一閃而過,接下來測試一下是否安裝啓動成功;

 

à在任務管理器的進程中查看nginx.exe是否啓動

 

à若看到該映像名稱,證明nginx程序已經啓動成功!

這時我們就可以在瀏覽器中訪問:http://localhost

 

à這樣我們就成功的搭建了一個nginx服務!!

 

二:分別在另外兩臺計算機上配置tomcat以及部署項目,這裏就簡單說一個,另一臺類似;

下載安裝apache-tomcat-6.0.37.zip,解壓目錄爲:D:/web

配置環境變量參考地址:

http://wenku.baidu.com/link?url=ZFW-uT63qENQgiyOLZc8hkAeXrqvvGqV8eM-Q5yMb79bd_tqNmy-3RcHr1swKFa_FY_p-ofg-qxM6QNkYKLv-d3LbAO3XTXLyW5R9WL5yP3

192.168.101.222上的tomcat配置文件(\bin\server.xml):

<?xml version='1.0' encoding='utf-8'?>

<!--

  Licensed to the Apache Software Foundation (ASF) under one or more

  contributor license agreements.  See the NOTICE file distributed with

  this work for additional information regarding copyright ownership.

  The ASF licenses this file to You under the Apache License, Version 2.0

  (the "License"); you may not use this file except in compliance with

  the License.  You may obtain a copy of the License at

 

      http://www.apache.org/licenses/LICENSE-2.0

 

  Unless required by applicable law or agreed to in writing, software

  distributed under the License is distributed on an "AS IS" BASIS,

  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

  See the License for the specific language governing permissions and

  limitations under the License.

-->

<!-- Note:  A "Server" is not itself a "Container", so you may not

     define subcomponents such as "Valves" at this level.

     Documentation at /docs/config/server.html

 -->

<Server port="8006" shutdown="SHUTDOWN">

 

  <!--APR library loader. Documentation at /docs/apr.html -->

  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->

  <Listener className="org.apache.catalina.core.JasperListener" />

  <!-- Prevent memory leaks due to use of particular java/javax APIs-->

  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />

  <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->

  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />

  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

 

  <!-- Global JNDI resources

       Documentation at /docs/jndi-resources-howto.html

  -->

  <GlobalNamingResources>

    <!-- Editable user database that can also be used by

         UserDatabaseRealm to authenticate users

    -->

    <Resource name="UserDatabase" auth="Container"

              type="org.apache.catalina.UserDatabase"

              description="User database that can be updated and saved"

              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"

              pathname="conf/tomcat-users.xml" />

  </GlobalNamingResources>

 

  <!-- A "Service" is a collection of one or more "Connectors" that share

       a single "Container" Note:  A "Service" is not itself a "Container", 

       so you may not define subcomponents such as "Valves" at this level.

       Documentation at /docs/config/service.html

   -->

  <Service name="Catalina">

  

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->

    <!--

    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 

        maxThreads="150" minSpareThreads="4"/>

    -->

    

    

    <!-- A "Connector" represents an endpoint by which requests are received

         and responses are returned. Documentation at :

         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)

         Java AJP  Connector: /docs/config/ajp.html

         APR (HTTP/AJP) Connector: /docs/apr.html

         Define a non-SSL HTTP/1.1 Connector on port 8080

    -->

    <Connector port="8088" protocol="HTTP/1.1" 

               connectionTimeout="20000" 

               redirectPort="8443" URIEncoding="UTF-8"/>

    <!-- A "Connector" using the shared thread pool-->

    <!--

    <Connector executor="tomcatThreadPool"

               port="8080" protocol="HTTP/1.1" 

               connectionTimeout="20000" 

               redirectPort="8443" />

    -->           

    <!-- Define a SSL HTTP/1.1 Connector on port 8443

         This connector uses the JSSE configuration, when using APR, the 

         connector should be using the OpenSSL style configuration

         described in the APR documentation -->

    <!--

    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"

               maxThreads="150" scheme="https" secure="true"

               clientAuth="false" sslProtocol="TLS" />

    -->

 

    <!-- Define an AJP 1.3 Connector on port 8009 -->

    <Connector port="8008" protocol="AJP/1.3" redirectPort="8443" />

 

 

    <!-- An Engine represents the entry point (within Catalina) that processes

         every request.  The Engine implementation for Tomcat stand alone

         analyzes the HTTP headers included with the request, and passes them

         on to the appropriate Host (virtual host).

         Documentation at /docs/config/engine.html -->

 

    <!-- You should set jvmRoute to support load-balancing via AJP ie :

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">         

    --> 

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">

 

      <!--For clustering, please take a look at documentation at:

          /docs/cluster-howto.html  (simple how to)

          /docs/config/cluster.html (reference documentation) -->

      <!--

      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>

      -->        

      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" 
                channelSendOptions="6">
       
                <Manager className="org.apache.catalina.ha.session.DeltaManager" 
                expireSessionsOnShutdown="false" 
                notifyListenersOnReplication="true"/>
        
          <Channel className="org.apache.catalina.tribes.group.GroupChannel"> 

                <Membership className="org.apache.catalina.tribes.membership.McastService"   

                    address="228.0.0.4"  

                    port="45564"  

                    frequency="500"  

                    dropTime="3000"/>  
                <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"   

                    address="192.168.101.222"  

                    autoBind="100"  

                    port="4001"   

                    selectorTimeout="100"  maxThreads="6"/>  
               <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">  
                    <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>                
              </Sender>  

                <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>  

                <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/> 

            </Channel>  
     <Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;"/>  

           <ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
           <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/> 

           </Cluster>

 

 

 

      <!-- The request dumper valve dumps useful debugging information about

           the request and response data received and sent by Tomcat.

           Documentation at: /docs/config/valve.html -->

      <!--

      <Valve className="org.apache.catalina.valves.RequestDumperValve"/>

      -->

 

      <!-- This Realm uses the UserDatabase configured in the global JNDI

           resources under the key "UserDatabase".  Any edits

           that are performed against this UserDatabase are immediately

           available for use by the Realm.  -->

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"

             resourceName="UserDatabase"/>

 

      <!-- Define the default virtual host

           Note: XML Schema validation will not work with Xerces 2.2.

       -->

<!--

下面是部署項目路徑

-->

      <Host name="localhost"  appBase="webapps"

            unpackWARs="true" autoDeploy="true"

            xmlValidation="false" xmlNamespaceAware="false">

<Context path=""  docBase="D:\web\apache-tomcat-6.0.37/webapps/p2b"></Context>

      </Host>

    </Engine>

  </Service>

</Server>

tomcatweb.xml文件中的</web-app>前面加上<distributable/>即可

 

192.168.101.5計算機上的tomcat配置文件:

 

<?xml version='1.0' encoding='utf-8'?>

<!--

  Licensed to the Apache Software Foundation (ASF) under one or more

  contributor license agreements.  See the NOTICE file distributed with

  this work for additional information regarding copyright ownership.

  The ASF licenses this file to You under the Apache License, Version 2.0

  (the "License"); you may not use this file except in compliance with

  the License.  You may obtain a copy of the License at

 

      http://www.apache.org/licenses/LICENSE-2.0

 

  Unless required by applicable law or agreed to in writing, software

  distributed under the License is distributed on an "AS IS" BASIS,

  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

  See the License for the specific language governing permissions and

  limitations under the License.

-->

<!-- Note:  A "Server" is not itself a "Container", so you may not

     define subcomponents such as "Valves" at this level.

     Documentation at /docs/config/server.html

 -->

<Server port="8005" shutdown="SHUTDOWN">

 

  <!--APR library loader. Documentation at /docs/apr.html -->

  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->

  <Listener className="org.apache.catalina.core.JasperListener" />

  <!-- Prevent memory leaks due to use of particular java/javax APIs-->

  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />

  <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->

  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />

  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

 

  <!-- Global JNDI resources

       Documentation at /docs/jndi-resources-howto.html

  -->

  <GlobalNamingResources>

    <!-- Editable user database that can also be used by

         UserDatabaseRealm to authenticate users

    -->

    <Resource name="UserDatabase" auth="Container"

              type="org.apache.catalina.UserDatabase"

              description="User database that can be updated and saved"

              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"

              pathname="conf/tomcat-users.xml" />

  </GlobalNamingResources>

 

  <!-- A "Service" is a collection of one or more "Connectors" that share

       a single "Container" Note:  A "Service" is not itself a "Container", 

       so you may not define subcomponents such as "Valves" at this level.

       Documentation at /docs/config/service.html

   -->

  <Service name="Catalina">

  

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->

    <!--

    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 

        maxThreads="150" minSpareThreads="4"/>

    -->

    

    

    <!-- A "Connector" represents an endpoint by which requests are received

         and responses are returned. Documentation at :

         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)

         Java AJP  Connector: /docs/config/ajp.html

         APR (HTTP/AJP) Connector: /docs/apr.html

         Define a non-SSL HTTP/1.1 Connector on port 8080

    -->

    <Connector port="8081" protocol="HTTP/1.1" 

               connectionTimeout="20000" 

               redirectPort="8443" URIEncoding="UTF-8"/>

    <!-- A "Connector" using the shared thread pool-->

    <!--

    <Connector executor="tomcatThreadPool"

               port="8080" protocol="HTTP/1.1" 

               connectionTimeout="20000" 

               redirectPort="8443"/>

    -->           

    <!-- Define a SSL HTTP/1.1 Connector on port 8443

         This connector uses the JSSE configuration, when using APR, the 

         connector should be using the OpenSSL style configuration

         described in the APR documentation -->

    <!--

    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"

               maxThreads="150" scheme="https" secure="true"

               clientAuth="false" sslProtocol="TLS" />

    -->

 

    <!-- Define an AJP 1.3 Connector on port 8009 -->

    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

 

 

    <!-- An Engine represents the entry point (within Catalina) that processes

         every request.  The Engine implementation for Tomcat stand alone

         analyzes the HTTP headers included with the request, and passes them

         on to the appropriate Host (virtual host).

         Documentation at /docs/config/engine.html -->

 

    <!-- You should set jvmRoute to support load-balancing via AJP ie :

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">         

    --> 

    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat2">

 

      <!--For clustering, please take a look at documentation at:

          /docs/cluster-howto.html  (simple how to)

          /docs/config/cluster.html (reference documentation) -->

      <!--

      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>

      -->        

       <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" 
                channelSendOptions="6">
       
                <Manager className="org.apache.catalina.ha.session.DeltaManager" 
                expireSessionsOnShutdown="false" 
                notifyListenersOnReplication="true"/>
        
          <Channel className="org.apache.catalina.tribes.group.GroupChannel"> 

                <Membership className="org.apache.catalina.tribes.membership.McastService"   

                    address="228.0.0.4"  

                    port="45564"  

                    frequency="500"  

                    dropTime="3000"/>  
                <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"   

                    address="192.168.101.5"  

                    autoBind="100"  

                    port="4001"   

                    selectorTimeout="100"  maxThreads="6"/>  
               <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">  
                    <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>                
              </Sender>  

                <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>  

                <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/> 

            </Channel>  
     <Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;"/>  

           <ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
           <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/> 

           </Cluster>

 

      <!-- The request dumper valve dumps useful debugging information about

           the request and response data received and sent by Tomcat.

           Documentation at: /docs/config/valve.html -->

      <!--

      <Valve className="org.apache.catalina.valves.RequestDumperValve"/>

      -->

 

      <!-- This Realm uses the UserDatabase configured in the global JNDI

           resources under the key "UserDatabase".  Any edits

           that are performed against this UserDatabase are immediately

           available for use by the Realm.  -->

      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"

             resourceName="UserDatabase"/>

 

      <!-- Define the default virtual host

           Note: XML Schema validation will not work with Xerces 2.2.

       -->

      <Host name="localhost"  appBase="webapps"

            unpackWARs="true" autoDeploy="true"

            xmlValidation="false" xmlNamespaceAware="false">

<Context path=""  docBase="D:/apache-tomcat-6.0.37-windows-x86/apache-tomcat-6.0.37/webapps/p2b"></Context>

      </Host>

    </Engine>

  </Service>

</Server>

tomcatweb.xml文件中的</web-app>前面加上<distributable/>即可

三、啓動tomcat服務;

  

分別到兩個tomcat下直接雙擊bin\startup.bat啓動tomcat,如圖所示:

 

 

通過瀏覽器分別訪問兩臺機器的tomcat,顯示項目p2b的主頁面,即可說明tomcat配置成功!

 

 

 

 

 

Nginx+Tomcat負載均衡配置這裏只需要修改Nginx的配置文件nginx.conf,讓它通過tomcat來轉發。

Nginx配置文件完成如下:


#使用的用戶和組,window下不指定

#user  nobody;

#指定工作衍生進程數(一般等於CPU總和數或總和數的兩倍,例如兩個四核CPU,則總和數爲8)

worker_processes  1;

#指定錯誤日誌文件存放路徑,錯誤日誌級別可選項爲【debug|info|notice|warn|error|crit

#error_log  logs/error.log;

#error_log  logs/error.log  notice;

#error_log  logs/error.log  info;

#指定pid存放路徑

#pid        logs/nginx.pid;

 

#工作模式及連接數上限

events {

#使用網絡I/O模型,Linux系統推薦使用epoll模型,FreeBSD系統推薦使用kqueue;window下不指定

#允許的連接數

#user epoll;

    worker_connections  100;

}

 

#設定http服務器,利用他的反向代理功能提供負載均衡支持

http {

#設定mime類型

    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"';

    client_header_buffer_size 1k;

    large_client_header_buffers 4 4k;

 

access_log  logs/access.log  main;

#設定access log

    client_header_timeout 3m;

    client_body_timeout 3m;

    send_timeout 3m;

    sendfile        on;

    tcp_nopush     on;

    tcp_nodelay on;

    #keepalive_timeout  0;

    keepalive_timeout  65;

#開啓gzip模塊

    gzip  on;

    gzip_min_length 1100;

    gzip_buffers 4 8k;

    gzip_types text/plain application/x-javascript text/css application/xml;

    output_buffers 1 32k; 

    postpone_output 1460;

    server_names_hash_bucket_size 128; 

    client_max_body_size 8m;

    fastcgi_connect_timeout 300; 

    fastcgi_send_timeout 300; 

    fastcgi_read_timeout 300; 

    fastcgi_buffer_size 64k; 

    fastcgi_buffers 4 64k; 

    fastcgi_busy_buffers_size 128k; 

    fastcgi_temp_file_write_size 128k; 

    gzip_http_version 1.1; 

    gzip_comp_level 2; 

gzip_vary on;

#設定負載均衡的服務器列表

upstream localhost {

#設定負載均衡的服務器列表

      #ip_hash;

#同一機器在多網情況下,路由切換,ip可能不同 
#weigth參數表示權值,權值越高被分配到的機率越大

      server 192.168.101.222:8088 max_fails=2 fail_timeout=600s;

      server 192.168.101.5:8081 max_fails=2 fail_timeout=600s; 

}

#設定虛擬主機

    server {

        listen       80;

        server_name  localhost;

 

        charset UTF-8;

#設定本虛擬主機的訪問日誌

        access_log  logs/host.access.log  main;

#對 "/" 啓用負載均衡

        location / {

            root   \\192.168.101.222\D:\web\apache-tomcat-6.0.37\webapps;

            index  index.html index.htm index.aspx;

            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 12;

#連接成功後 等待後端服務器響應時間 其實已進入後端的排隊之中等候處理

            proxy_read_timeout 90;

#代理請求緩存區 這個緩存區間會保存用戶的頭信息一共Nginx進行規則處理 一般只要能保存下頭信息即可

            proxy_send_timeout 90;

#同上 告訴Nginx保存單個用的幾個Buffer最大用多大空間

            proxy_buffer_size 4k;

            proxy_buffers 4 32k;

#如果系統很忙的時候可以申請國內各大的proxy_buffers 官方推薦 *2

            proxy_busy_buffers_size 64k;

#proxy 緩存臨時文件的大小

            proxy_temp_file_write_size 64k; 

            proxy_next_upstream error timeout invalid_header http_500 http_503 http_404; 

            proxy_max_temp_file_size 128m;

            proxy_pass http://localhost;

        }

        

 

        #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;

        }

 

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80

        #

        #location ~ \.php$ {

        #    proxy_pass   http://127.0.0.1;

        #}

 

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

        #

        #location ~ \.php$ {

        #    root           html;

        #    fastcgi_pass   127.0.0.1:9000;

        #    fastcgi_index  index.php;

        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

        #    include        fastcgi_params;

        #}

 

        # 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 ssl;

    #    server_name  localhost;

 

    #    ssl_certificate      cert.pem;

    #    ssl_certificate_key  cert.key;

 

    #    ssl_session_cache    shared:SSL:1m;

    #    ssl_session_timeout  5m;

 

    #    ssl_ciphers  HIGH:!aNULL:!MD5;

    #    ssl_prefer_server_ciphers  on;

 

    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}

 

}

四、測試 

前提是分別啓動兩臺機器的tomcat,其次啓動nginx服務;

192.168.101.23上訪問nginx服務器(通過訪問http://localhost來實現對192.168.101.222192.168.101.5這兩個機器上應用程序的訪問,最終實現tomcat的均衡負載)

[1]關閉192.168.101.222上的tomcat服務,訪問192.168.101.23上的nginx服務,觀察192.168.101.5上的tomcat是否運行;

[2]關閉192.168.101.5上的tomcat服務,訪問192.168.101.23上的nginx服務,觀察192.168.101.222上的tomcat是否運行;

[3]兩個tomcat都啓動,訪問nginx服務,模擬併發用戶n個,觀察tomcat的運行情況;

如果[1][2]tomcat都運行就說明搭建nginx代理服務成功,tomcat實現了均衡負載;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章