Windows环境下Nginx+Tomcat+Redis实现应用服务器集群负载均衡和Session共享

1.实验环境和所需软件

   1.Windows7环境

   2.nginx 1.6.3

   3.redis 2.6.2

   4.Tomcat 7.0.56


 2.配置Nginx

         
[java]  view plain  copy
  1. Nginx路径:E:\new\Tomcat_Nginx_Cluster\nginx-1.6.3\  
[java]  view plain  copy
  1. #Nginx所有用户和组,window下不指定  
  2. #user Adminstrator  
  3. #user  nobody;  
  4. #工作的子进程数量(通常等于CPU核数或者2倍与CPU核数)  
  5. worker_processes  4;  
  6.   
  7. #错误日志存放路径  
  8. #error_log  logs/error.log;  
  9. #error_log  logs/error.log  notice;  
  10. #error_log  logs/error.log  info;  
  11.   
  12. #指定pid存放文件  
  13. #pid        logs/nginx.pid;  
  14.   
  15.   
  16. events {  
  17. #使用网络IO模型,Linux建议用epoll,FreeBSD建议用kqueue,window下不指定  
  18. #use epoll  
  19. #设置单个进程同时打开的最大连接数  
  20.     worker_connections  1024;  
  21. }  
  22.   
  23.   
  24. http {  
  25.     include       mime.types;  
  26.     default_type  application/octet-stream;  
  27.   
  28. #定义日志格式  
  29.     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '  
  30.     #                  '$status $body_bytes_sent "$http_referer" '  
  31.     #                  '"$http_user_agent" "$http_x_forwarded_for"';  
  32.   
  33.     #access_log  logs/access.log  main;  
  34.   
  35.     sendfile        on;  
  36.     #tcp_nopush     on;  
  37.   
  38.     #keepalive_timeout  0;  
  39.     #http连接的持续时间  
  40.     keepalive_timeout  65;  
  41.       
  42. #gzip压缩设置  
  43.     #gzip  on; #是否打开gzip压缩,默认不打开  
  44.     gzip_min_length 1k;  #最小压缩文件大小  
  45.     gzip_buffers 4 16k;  #压缩缓冲区  
  46.     #http的协议版本(1.0/1.1),默认1.1,前端如果是squid2.5请使用1.0  
  47.     gzip_http_version 1.1;  
  48.     #gzip压缩比,1压缩比最小处理速度最快,9压缩比最大但处理速度最慢(传输快但比较消耗cpu)  
  49.     gzip_comp_level 2;     
  50.     #和http头有关系,加个vary头,给代理服务器用的,有的浏览器支持压缩,有的不支持,所以避免浪费不支持的也压缩,所以根据客户端的HTTP头来判断,是否需要压缩  
  51.     gzip_vary on;  
  52.     #gzip压缩类型,不用添加text/html,否则会有警告信息  
  53.     gzip_types text/plain text/javascript text/css application/xmlapplication/x-javascript application/json;  
  54.   
  55.   
  56. #设定负载均衡的服务器列表,可以配置多个upstream,但mysvr名字要区分  
  57. #下面配置请求的负载分配  
  58.     upstream localhost {  
  59.       #根据ip计算将请求分配给那个后端Tomcat,注意:这里并不能解决Session共享问题  
  60.       #同一机器在多网情况下,路由切换,ip可能不同  
  61.       #ip_hash  
  62.       #weight参数表示权值,权值越高被分配到的几率越大,一般在生产环境中,需要根据访问情况制定相应算法  
  63.       server localhost:8080 weight=5;  
  64.       server localhost:8081 weight=5;  
  65.     }  
  66.   
  67.     server {  
  68.         #Nginx监听的端口号  
  69.         listen       80;  
  70.     #域名可有多个,用空格隔开  
  71.         server_name  localhost;  
  72.   
  73.         #字符编码集  
  74.         #charset koi8-r;  
  75.     charset utf-8;  
  76.   
  77.         #设定本虚拟主机的访问日志。关闭日志可减少IO,提高性能  
  78.         #access_log  logs/host.access.log  main;  
  79.   
  80.         #默认请求  
  81.         location / {  
  82.         #定义服务器的默认网站根目录位置  
  83.             #root   html;  
  84.         root E:\new\Tomcat_Nginx_Cluster;  
  85.         #定义首页  
  86.             index  index.html index.htm index.jsp;  
  87.         #请求专项mysvr定义的服务器列表  
  88.         #配置端口转发,proxy_pass  
  89.         proxy_pass http://localhost;  
  90.         proxy_redirect default;  
  91.         #与代理服务器连接的超时时间,必须留意这个timeout不能超过75秒,当一台服务器宕机时,过10秒转发到另外一台服务器  
  92.         proxy_connect_timeout 10;  
  93.         }  
  94.   
  95.         location ~ .*.jsp$ #所有jsp的页面均交由tomcat处理  
  96.         {  
  97.              index index.jsp;  
  98.                  proxy_pass http://localhost;#转向tomcat处理  
  99.         }  
  100.   
  101.     location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ #设定访问静态文件直接读取不经过tomcat  
  102.         {  
  103.          #设置静态资源的过期时间  
  104.              expires 30d;  
  105.         }  
  106.   
  107.         #定义几种常见的错误页面:404,400,500等  
  108.         #error_page  404              /404.html;  
  109.   
  110.         # redirect server error pages to the static page /50x.html  
  111.         #  
  112.         error_page   500 502 503 504  /50x.html;  
  113.         location = /50x.html {  
  114.             root   html;  
  115.         }  
  116.   
  117.   
  118.     #对本server"/"启用负载均衡    
  119.         #location / {    
  120.         #    proxy_pass http://mysvr;    
  121.         #    proxy_redirect off;    
  122.         #    proxy_set_header Host $host;    
  123.         #    proxy_set_header X-Real-IP $remote_addr;    
  124.         #    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    
  125.         #    client_max_body_size 10m;    
  126.         #    client_body_buffer_size 128k;    
  127.         #    proxy_connect_timeout 90;    
  128.         #    proxy_send_timeout 90;    
  129.         #    proxy_read_timeout 90;    
  130.         #    proxy_buffer_size 4k;    
  131.         #    proxy_buffers 4 32k;    
  132.         #    proxy_busy_buffers_size 64k;    
  133.         #    proxy_temp_file_write_size 64k;    
  134.         #}    
  135.   
  136.         # proxy the PHP scripts to Apache listening on 127.0.0.1:80  
  137.         #  
  138.         #location ~ \.php$ {  
  139.         #    proxy_pass   http://127.0.0.1;  
  140.         #}  
  141.   
  142.         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000  
  143.         #  
  144.         #location ~ \.php$ {  
  145.         #    root           html;  
  146.         #    fastcgi_pass   127.0.0.1:9000;  
  147.         #    fastcgi_index  index.php;  
  148.         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;  
  149.         #    include        fastcgi_params;  
  150.         #}  
  151.   
  152.         # deny access to .htaccess files, if Apache's document root  
  153.         # concurs with nginx's one  
  154.         #  
  155.         #location ~ /\.ht {  
  156.         #    deny  all;  
  157.         #}  
  158.     }  
  159.   
  160.   
  161.     # another virtual host using mix of IP-, name-, and port-based configuration  
  162.     #  
  163.     #server {  
  164.     #    listen       8000;  
  165.     #    listen       somename:8080;  
  166.     #    server_name  somename  alias  another.alias;  
  167.   
  168.     #    location / {  
  169.     #        root   html;  
  170.     #        index  index.html index.htm;  
  171.     #    }  
  172.     #}  
  173.   
  174.   
  175.     # HTTPS server  
  176.     #  
  177.     #server {  
  178.     #    listen       443 ssl;  
  179.     #    server_name  localhost;  
  180.   
  181.     #    ssl_certificate      cert.pem;  
  182.     #    ssl_certificate_key  cert.key;  
  183.   
  184.     #    ssl_session_cache    shared:SSL:1m;  
  185.     #    ssl_session_timeout  5m;  
  186.   
  187.     #    ssl_ciphers  HIGH:!aNULL:!MD5;  
  188.     #    ssl_prefer_server_ciphers  on;  
  189.   
  190.     #    location / {  
  191.     #        root   html;  
  192.     #        index  index.html index.htm;  
  193.     #    }  
  194.     #}  
  195.   
  196. }  

 3.配置两个Tomcat

         1. 在两个Tomcat的lib中导入连接redis需要的jar包:


             
 

         2.配置两个Tomcat通过redis共享session


         Tomcat-8080          ---        localhost:8080

                           1.conf/server.xml端口配置   ---   使用默认的8080端口,只需配置这个Tomcat了

   Engine元素增加jvmRoute属性:
[html]  view plain copy
  1. <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat8080">    
 

                           2.conf/context.xml配置         ---   连接redis共享session的配置

[html]  view plain  copy
  1. <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />  
  2.     <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"  
  3.          host="localhost"  
  4.          port="6379"   
  5.          database="0"   
  6.          maxInactiveInterval="60" />  


完整配置:
                           
[html]  view plain  copy
  1. <span style="font-family: Arial, Helvetica, sans-serif;"><?xml version='1.0' encoding='utf-8'?></span>  
[html]  view plain  copy
  1. <?xml version='1.0' encoding='utf-8'?><!--  
  2.   Licensed to the Apache Software Foundation (ASF) under one or more  
  3.   contributor license agreements.  See the NOTICE file distributed with  
  4.   this work for additional information regarding copyright ownership.  
  5.   The ASF licenses this file to You under the Apache License, Version 2.0  
  6.   (the "License"); you may not use this file except in compliance with  
  7.   the License.  You may obtain a copy of the License at  
  8.   
  9.       http://www.apache.org/licenses/LICENSE-2.0  
  10.   
  11.   Unless required by applicable law or agreed to in writing, software  
  12.   distributed under the License is distributed on an "AS IS" BASIS,  
  13.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  14.   See the License for the specific language governing permissions and  
  15.   limitations under the License.  
  16. -->  
  17. <!-- The contents of this file will be loaded for each web application -->  
  18. <Context>  
  19.   
  20.     <!-- Default set of monitored resources -->  
  21.     <WatchedResource>WEB-INF/web.xml</WatchedResource>  
  22.   
  23.     <!-- Uncomment this to disable session persistence across Tomcat restarts -->  
  24.     <!-- 
  25.     <Manager pathname="" /> 
  26.     -->  
  27.   
  28.     <!-- Uncomment this to enable Comet connection tacking (provides events  
  29.          on session expiration as well as webapp lifecycle) -->  
  30.     <!-- 
  31.     <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> 
  32.     -->  
  33.   
  34. <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />  
  35.     <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"  
  36.          host="localhost"  
  37.          port="6379"   
  38.          database="0"   
  39.          maxInactiveInterval="60" />  
  40.   
  41. </Context>  

         Tomcat-8081          ---        localhost:8081
          
                           1.conf/server.xml端口配置   ---   使用8081端口,需要在server.xml中进行相应的配置(4个地方需要修改端口)
                             

第一处端口修改:

[html]  view plain copy
  1. <!--  修改port端口:8006 俩个tomcat不能重复,端口随意,别太小-->    
  2. <Server port="8006" shutdown="SHUTDOWN">   
第二处端口修改:
[html]  view plain copy
  1. <!-- port="8081" tomcat监听端口,随意设置,别太小 -->    
  2. <Connector port="8081" protocol="HTTP/1.1"      
  3.                connectionTimeout="20000"      
  4.                redirectPort="8443" />    
第三处端口修改:
[html]  view plain copy
  1. <Connector port="18009" protocol="AJP/1.3" redirectPort="18443" />   
Engine元素增加jvmRoute属性:
[html]  view plain copy
  1. <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat8081">    
 
                               完整配置:
                               
[html]  view plain  copy
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!--  
  3.   Licensed to the Apache Software Foundation (ASF) under one or more  
  4.   contributor license agreements.  See the NOTICE file distributed with  
  5.   this work for additional information regarding copyright ownership.  
  6.   The ASF licenses this file to You under the Apache License, Version 2.0  
  7.   (the "License"); you may not use this file except in compliance with  
  8.   the License.  You may obtain a copy of the License at  
  9.   
  10.       http://www.apache.org/licenses/LICENSE-2.0  
  11.   
  12.   Unless required by applicable law or agreed to in writing, software  
  13.   distributed under the License is distributed on an "AS IS" BASIS,  
  14.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  15.   See the License for the specific language governing permissions and  
  16.   limitations under the License.  
  17. -->  
  18. <!-- Note:  A "Server" is not itself a "Container", so you may not  
  19.      define subcomponents such as "Valves" at this level.  
  20.      Documentation at /docs/config/server.html  
  21.  -->  
  22. <Server port="8006" shutdown="SHUTDOWN">  
  23.   <!-- Security listener. Documentation at /docs/config/listeners.html  
  24.   <Listener className="org.apache.catalina.security.SecurityListener" />  
  25.   -->  
  26.   <!--APR library loader. Documentation at /docs/apr.html -->  
  27.   <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />  
  28.   <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->  
  29.   <Listener className="org.apache.catalina.core.JasperListener" />  
  30.   <!-- Prevent memory leaks due to use of particular java/javax APIs-->  
  31.   <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />  
  32.   <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />  
  33.   <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />  
  34.   
  35.   <!-- Global JNDI resources  
  36.        Documentation at /docs/jndi-resources-howto.html  
  37.   -->  
  38.   <GlobalNamingResources>  
  39.     <!-- Editable user database that can also be used by  
  40.          UserDatabaseRealm to authenticate users  
  41.     -->  
  42.     <Resource name="UserDatabase" auth="Container"  
  43.               type="org.apache.catalina.UserDatabase"  
  44.               description="User database that can be updated and saved"  
  45.               factory="org.apache.catalina.users.MemoryUserDatabaseFactory"  
  46.               pathname="conf/tomcat-users.xml" />  
  47.   </GlobalNamingResources>  
  48.   
  49.   <!-- A "Service" is a collection of one or more "Connectors" that share  
  50.        a single "Container" Note:  A "Service" is not itself a "Container",  
  51.        so you may not define subcomponents such as "Valves" at this level.  
  52.        Documentation at /docs/config/service.html  
  53.    -->  
  54.   <Service name="Catalina">  
  55.   
  56.     <!--The connectors can use a shared executor, you can define one or more named thread pools-->  
  57.     <!--  
  58.     <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"  
  59.         maxThreads="150" minSpareThreads="4"/>  
  60.     -->  
  61.   
  62.   
  63.     <!-- A "Connector" represents an endpoint by which requests are received  
  64.          and responses are returned. Documentation at :  
  65.          Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)  
  66.          Java AJP  Connector: /docs/config/ajp.html  
  67.          APR (HTTP/AJP) Connector: /docs/apr.html  
  68.          Define a non-SSL HTTP/1.1 Connector on port 8080  
  69.     -->  
  70.     <Connector port="8081" protocol="HTTP/1.1"  
  71.                connectionTimeout="20000"  
  72.                redirectPort="18443" />  
  73.     <!-- A "Connector" using the shared thread pool-->  
  74.     <!--  
  75.     <Connector executor="tomcatThreadPool"  
  76.                port="8080" protocol="HTTP/1.1"  
  77.                connectionTimeout="20000"  
  78.                redirectPort="8443" />  
  79.     -->  
  80.     <!-- Define a SSL HTTP/1.1 Connector on port 8443  
  81.          This connector uses the BIO implementation that requires the JSSE  
  82.          style configuration. When using the APR/native implementation, the  
  83.          OpenSSL style configuration is required as described in the APR/native  
  84.          documentation -->  
  85.     <!--  
  86.     <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"  
  87.                maxThreads="150" SSLEnabled="true" scheme="https" secure="true"  
  88.                clientAuth="false" sslProtocol="TLS" />  
  89.     -->  
  90.   
  91.     <!-- Define an AJP 1.3 Connector on port 8009 -->  
  92.     <Connector port="18009" protocol="AJP/1.3" redirectPort="18443" />  
  93.   
  94.   
  95.     <!-- An Engine represents the entry point (within Catalina) that processes  
  96.          every request.  The Engine implementation for Tomcat stand alone  
  97.          analyzes the HTTP headers included with the request, and passes them  
  98.          on to the appropriate Host (virtual host).  
  99.          Documentation at /docs/config/engine.html -->  
  100.   
  101.     <!-- You should set jvmRoute to support load-balancing via AJP ie :  
  102.     <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">  
  103.     -->  
  104.     <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat8081">  
  105.   
  106.       <!--For clustering, please take a look at documentation at:  
  107.           /docs/cluster-howto.html  (simple how to)  
  108.           /docs/config/cluster.html (reference documentation) -->  
  109.       <!-- 
  110.       <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> 
  111.       -->  
  112.   
  113.       <!-- Use the LockOutRealm to prevent attempts to guess user passwords  
  114.            via a brute-force attack -->  
  115.       <Realm className="org.apache.catalina.realm.LockOutRealm">  
  116.         <!-- This Realm uses the UserDatabase configured in the global JNDI  
  117.              resources under the key "UserDatabase".  Any edits  
  118.              that are performed against this UserDatabase are immediately  
  119.              available for use by the Realm.  -->  
  120.         <Realm className="org.apache.catalina.realm.UserDatabaseRealm"  
  121.                resourceName="UserDatabase"/>  
  122.       </Realm>  
  123.   
  124.       <Host name="localhost"  appBase="webapps"  
  125.             unpackWARs="true" autoDeploy="true">  
  126.   
  127.         <!-- SingleSignOn valve, share authentication between web applications  
  128.              Documentation at: /docs/config/valve.html -->  
  129.         <!-- 
  130.         <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> 
  131.         -->  
  132.   
  133.         <!-- Access log processes all example.  
  134.              Documentation at: /docs/config/valve.html  
  135.              Note: The pattern used is equivalent to using pattern="common" -->  
  136.         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"  
  137.                prefix="localhost_access_log." suffix=".txt"  
  138.                pattern="%h %l %u %t "%r" %s %b" />  
  139.   
  140.       </Host>  
  141.     </Engine>  
  142.   </Service>  
  143. </Server>  



                           2.conf/context.xml配置         ---   连接redis共享session的配置

 4.启动nginx、redis和两个Tomcat组建集群

       1.创建index.jsp测试文件

                在两个Tomcat的webapps下面创建一个test目录,并创建一个index.jsp文件
[html]  view plain  copy
  1. <%@ page language="java" %>    
  2. <html>    
  3.   <head><title>TomcatA</title></head>    
  4.   <body>    
  5.      
  6.     <table align="centre" border="1">    
  7.       <tr>    
  8.         <td>Session ID</td>    
  9.         <td><%= session.getId() %></td>    
  10.       </tr>    
  11.       <tr>    
  12.         <td>Created on</td>    
  13.         <td><%= session.getCreationTime() %></td>    
  14.      </tr>    
  15.     </table>    
  16.   </body>    
  17. </html>    
  18. sessionID:<%=session.getId()%>     
  19. <br>     
  20. SessionIP:<%=request.getServerName()%>     
  21. <br>     
  22. SessionPort:<%=request.getServerPort()%>     
  23. <%     
  24. //为了区分,第二个可以是222    
  25. out.println("This is Tomcat Server 1111");     
  26. %>      


         2.先启动Nginx、再启动redis,最后启动两个Tomcat

                说明:
                        Windows下Nginx的启动与关闭
                               启动: E:\new\Tomcat_Nginx_Cluster\nginx-1.6.3>nginx.exe
                               关闭:E:\new\Tomcat_Nginx_Cluster\nginx-1.6.3>nginx -s quit

 5.测试Session共享

           打开浏览器去访问第一个Tomcat,然后再第二个Tomcat,页面Session信息如下




        直接访问Tomcat集群的到Session信息如下:


由图可以看到,三个Tomcat的SessionID都是一样的:9BE0CD81E96DCBEEC2DD4AD5E2A63D09,只要不关闭浏览器,不管怎么刷新,SessionID都是不变了。由此可以,三个Tomcat通过redis实现了Session信息共享。


CentOS下使用Memcached共享Session例子参考:Nginx+Tomcat7+Mencached负载均衡集群部署笔记

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值