1. 1、采用Nginx负载均衡 
  2. 2、memcached共享session 
  3. 3、tomcat集群配置(3台CentOS 6) 
  4.  
  5. (172.18.188.64): 操作系统CentOS 6; 安装nginx、memcached和tomcat 6 
  6. (172.18.188.76): 操作系统CentOS 6; 安装tomcat 6 
  7. (172.18.188.78): 操作系统CentOS 6; 安装tomcat 6 
  8.  
  9. nginx、memcached、tomcat 6安装省略. 
  10.  
  11. nginx配置如下: 
  12.  
  13. nginx.conf如下: 
  14. #运行nginx所在的用户名和用户组 
  15. #user  root root; 
  16.  
  17. #启动进程数 
  18. worker_processes 8; 
  19. #全局错误日志及PID文件 
  20. error_log /usr/local/webserver/nginx/logs/nginx_error.log crit; 
  21.  
  22. pid /usr/local/webserver/nginx/nginx.pid; 
  23.  
  24. #Specifies the value for maximum file descriptors that can be opened by this process. 
  25.  
  26. worker_rlimit_nofile 65535; 
  27. #工作模式及连接数上限 
  28. events 
  29.   use epoll; 
  30.   worker_connections 65535; 
  31. #设定http服务器,利用它的反向代理功能提供负载均衡支持 
  32. http 
  33.   #设定mime类型 
  34.   include       mime.types; 
  35.   default_type  application/octet-stream; 
  36.   include /usr/local/webserver/nginx/conf/proxy.conf; 
  37.   #charset  gb2312; 
  38.   #设定请求缓冲   
  39.   server_names_hash_bucket_size 128; 
  40.   client_header_buffer_size 32k; 
  41.   large_client_header_buffers 4 32k; 
  42.   #client_max_body_size 8m; 
  43.      
  44.   sendfile on; 
  45.   tcp_nopush     on; 
  46.  
  47.   keepalive_timeout 60; 
  48.  
  49.   tcp_nodelay on; 
  50.  
  51. #  fastcgi_connect_timeout 300; 
  52. #  fastcgi_send_timeout 300; 
  53. #  fastcgi_read_timeout 300; 
  54. #  fastcgi_buffer_size 64k; 
  55. #  fastcgi_buffers 4 64k; 
  56. #  fastcgi_busy_buffers_size 128k; 
  57. #  fastcgi_temp_file_write_size 128k; 
  58.  
  59.   gzip on; 
  60.   gzip_min_length  1k; 
  61.   gzip_buffers     4 16k; 
  62.   gzip_http_version 1.0; 
  63.   gzip_comp_level 2; 
  64.   gzip_types       text/plain application/x-javascript text/css application/xml; 
  65.   gzip_vary on; 
  66.  
  67.   #limit_zone  crawler  $binary_remote_addr  10m; 
  68. ###禁止通过ip访问站点 
  69. #  server{ 
  70. #       server_name _; 
  71. #       return 404; 
  72. #       } 
  73.  
  74. upstream tserver { 
  75.     server 172.18.188.64:8080 weight=1
  76.     server 172.18.188.76:8080 weight=1
  77.     server 172.18.188.78:8080 weight=1
  78.  
  79.   server 
  80.   { 
  81.     listen       80; 
  82.     server_name  vmwarehost; 
  83.     index index.html index.htm index.jsp; 
  84.     root  /home/www/web/ROOT; 
  85.  
  86.     #limit_conn   crawler  20;   
  87.     
  88.     location / 
  89.     { 
  90.     proxy_pass http://tserver; 
  91.     }  
  92.     
  93.     location /NginxStatus 
  94.     { 
  95.       stub_status on; 
  96.       access_log off; 
  97.     }    
  98.    
  99.     location ~ .*\.(htm|html|gif|jpg|jpeg|png|bmp|swf|ico)$ 
  100.     { 
  101.       expires      30d; 
  102.     } 
  103.  
  104.     location ~ .*\.(js|css)?$ 
  105.     { 
  106.       expires      1h; 
  107.     }   
  108.  
  109. #定义访问日志的写入格式 
  110.      log_format  access  '$remote_addr - $remote_user [$time_local] "$request" ' 
  111.               '$status $body_bytes_sent "$http_referer" ' 
  112.               '"$http_user_agent" $http_x_forwarded_for'; 
  113.               access_log  /usr/local/webserver/nginx/logs/localhost.log access; 
  114.  
  115.       } 
  116.  
  117.  
  118. proxy.confi配置如下 
  119. #!nginx (-) 
  120. # proxy.conf 
  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. tomcat 6 server.xml配置如下: 
  136. <?xml version='1.0' encoding='utf-8'?> 
  137. <!-- 
  138.   Licensed to the Apache Software Foundation (ASF) under one or more 
  139.   contributor license agreements.  See the NOTICE file distributed with 
  140.   this work for additional information regarding copyright ownership. 
  141.   The ASF licenses this file to You under the Apache License, Version 2.0 
  142.   (the "License"); you may not use this file except in compliance with 
  143.   the License.  You may obtain a copy of the License at 
  144.  
  145.       http://www.apache.org/licenses/LICENSE-2.0 
  146.  
  147.   Unless required by applicable law or agreed to in writing, software 
  148.   distributed under the License is distributed on an "AS IS" BASIS, 
  149.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  150.   See the License for the specific language governing permissions and 
  151.   limitations under the License. 
  152. --> 
  153. <!-- Note:  A "Server" is not itself a "Container", so you may not 
  154.      define subcomponents such as "Valves" at this level. 
  155.      Documentation at /docs/config/server.html 
  156. --> 
  157. <Server port="8005" shutdown="SHUTDOWN"> 
  158.  
  159.   <!--APR library loader. Documentation at /docs/apr.html --> 
  160.   <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /> 
  161.   <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html --> 
  162.   <Listener className="org.apache.catalina.core.JasperListener" /> 
  163.   <!-- Prevent memory leaks due to use of particular java/javax APIs--> 
  164.   <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> 
  165.   <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html --> 
  166.   <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" /> 
  167.   <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> 
  168.  
  169.   <!-- Global JNDI resources 
  170.        Documentation at /docs/jndi-resources-howto.html 
  171.   --> 
  172.   <GlobalNamingResources> 
  173.     <!-- Editable user database that can also be used by 
  174.          UserDatabaseRealm to authenticate users 
  175.     --> 
  176.     <Resource name="UserDatabase" auth="Container" 
  177.               type="org.apache.catalina.UserDatabase" 
  178.               description="User database that can be updated and saved" 
  179.               factory="org.apache.catalina.users.MemoryUserDatabaseFactory" 
  180.               pathname="conf/tomcat-users.xml" /> 
  181.   </GlobalNamingResources> 
  182.  
  183.   <!-- A "Service" is a collection of one or more "Connectors" that share 
  184.        a single "Container" Note:  A "Service" is not itself a "Container", 
  185.        so you may not define subcomponents such as "Valves" at this level. 
  186.        Documentation at /docs/config/service.html 
  187.    --> 
  188.   <Service name="Catalina"> 
  189.   
  190.     <!--The connectors can use a shared executor, you can define one or more named thread pools--> 
  191.     <!-- 
  192.     <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 
  193.         maxThreads="150" minSpareThreads="4"/> 
  194.     --> 
  195.     
  196.     
  197.     <!-- A "Connector" represents an endpoint by which requests are received 
  198.          and responses are returned. Documentation at : 
  199.          Java HTTP Connector: /docs/config/http.html (blocking & non-blocking) 
  200.          Java AJP  Connector: /docs/config/ajp.html 
  201.          APR (HTTP/AJP) Connector: /docs/apr.html 
  202.          Define a non-SSL HTTP/1.1 Connector on port 8080 
  203.     --> 
  204.     <Connector port="8080" protocol="HTTP/1.1" 
  205.                maxHttpHeaderSize="8192" connectionTimeout="20000" 
  206.                disableUploadTimeout="true" enableLookups="false" 
  207.                redirectPort="8443" maxThreads="600" 
  208.                minSpareThreads="25" maxSpareThreads="75" acceptCount="100" /> 
  209.     <!-- A "Connector" using the shared thread pool--> 
  210.     <!-- 
  211.     <Connector executor="tomcatThreadPool" 
  212.                port="8080" protocol="HTTP/1.1" 
  213.                connectionTimeout="20000" 
  214.                redirectPort="8443" /> 
  215.     -->           
  216.     <!-- Define a SSL HTTP/1.1 Connector on port 8443 
  217.          This connector uses the JSSE configuration, when using APR, the 
  218.          connector should be using the OpenSSL style configuration 
  219.          described in the APR documentation --> 
  220.     <!-- 
  221.     <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" 
  222.                maxThreads="150" scheme="https" secure="true" 
  223.                clientAuth="false" sslProtocol="TLS" /> 
  224.     --> 
  225.  
  226.     <!-- Define an AJP 1.3 Connector on port 8009 --> 
  227.     <Connector port="8009" protocol="AJP/1.3" 
  228.     maxHttpHeaderSize="8192" connectionTimeout="20000" 
  229.                   disableUploadTimeout="true" maxThreads="600" 
  230.                   minSpareThreads="25" maxSpareThreads="75" 
  231.                   enableLookups="false" redirectPort="8443" /> 
  232.  
  233.  
  234.     <!-- An Engine represents the entry point (within Catalina) that processes 
  235.          every request.  The Engine implementation for Tomcat stand alone 
  236.          analyzes the HTTP headers included with the request, and passes them 
  237.          on to the appropriate Host (virtual host). 
  238.          Documentation at /docs/config/engine.html --> 
  239.  
  240.     <!-- You should set jvmRoute to support load-balancing via AJP ie : 
  241.     <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">         
  242.     --> 
  243.     <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1"> 
  244.  
  245.       <!--For clustering, please take a look at documentation at: 
  246.           /docs/cluster-howto.html  (simple how to) 
  247.           /docs/config/cluster.html (reference documentation) --> 
  248.       
  249.          <!-- 
  250.       <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> 
  251.       --> 
  252.         <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" 
  253.                  channelSendOptions="6"> 
  254. <!-- 
  255. <Manager className="org.apache.catalina.ha.session.BackupManager" 
  256.                        expireSessionsOnShutdown="false" 
  257.                        notifyListenersOnReplication="true" 
  258.                        mapSendOptions="6"/> 
  259.            --> 
  260.            <!--            
  261.           <Manager className="org.apache.catalina.ha.session.DeltaManager" 
  262.                    expireSessionsOnShutdown="false" 
  263.                    notifyListenersOnReplication="true"/> 
  264. --> 
  265.           <Channel className="org.apache.catalina.tribes.group.GroupChannel"> 
  266.             <Membership className="org.apache.catalina.tribes.membership.McastService" 
  267.                         address="228.0.0.4" 
  268.                         port="45564" 
  269.                         frequency="500" 
  270.                         dropTime="3000"/> 
  271.             <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver" 
  272.                       address="172.18.188.64" 
  273.                       port="4001" 
  274.                       autoBind="100" 
  275.                       selectorTimeout="5000" 
  276.                       maxThreads="6"/> 
  277.  
  278.             <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter"> 
  279.               <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/> 
  280.             </Sender>         
  281.             <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/> 
  282.             <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/> 
  283.             <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>          
  284.           </Channel> 
  285.  
  286.           <Valve className="org.apache.catalina.ha.tcp.ReplicationValve" 
  287.           filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;" /> 
  288.  
  289.           <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer" 
  290.                         tempDir="/tmp/war-temp/" 
  291.                         deployDir="/tmp/war-deploy/" 
  292.                         watchDir="/tmp/war-listen/" 
  293.                         watchEnabled="false"/> 
  294.           <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/> 
  295.         </Cluster> 
  296.              
  297.  
  298.       <!-- The request dumper valve dumps useful debugging information about 
  299.            the request and response data received and sent by Tomcat. 
  300.            Documentation at: /docs/config/valve.html --> 
  301.       <!-- 
  302.       <Valve className="org.apache.catalina.valves.RequestDumperValve"/> 
  303.       --> 
  304.  
  305.       <!-- This Realm uses the UserDatabase configured in the global JNDI 
  306.            resources under the key "UserDatabase".  Any edits 
  307.            that are performed against this UserDatabase are immediately 
  308.            available for use by the Realm.  --> 
  309.       <Realm className="org.apache.catalina.realm.UserDatabaseRealm" 
  310.              resourceName="UserDatabase"/> 
  311.  
  312.       <!-- Define the default virtual host 
  313.            Note: XML Schema validation will not work with Xerces 2.2. 
  314.        --> 
  315.       <Host name="localhost"  appBase="/home/www/web" 
  316.             unpackWARs="true" autoDeploy="true" 
  317.             xmlValidation="false" xmlNamespaceAware="false"> 
  318.  
  319.         <!-- SingleSignOn valve, share authentication between web applications 
  320.              Documentation at: /docs/config/valve.html --> 
  321.         <!-- 
  322.         <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> 
  323.         --> 
  324.  
  325.         <!-- Access log processes all example. 
  326.              Documentation at: /docs/config/valve.html --> 
  327.         <!-- 
  328.         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"  
  329.                prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/> 
  330.         --> 
  331.       </Host> 
  332.     </Engine> 
  333.   </Service> 
  334. </Server> 
  335.  
  336. content.xml配置如下 
  337. <Context> 
  338.  
  339.     <!-- Default set of monitored resources --> 
  340.     <WatchedResource>WEB-INF/web.xml</WatchedResource> 
  341.  
  342.     <!-- Uncomment this to disable session persistence across Tomcat restarts --> 
  343.     <!-- 
  344.     <Manager pathname="" /> 
  345.     --> 
  346.  
  347.     <!-- Uncomment this to enable Comet connection tacking (provides events 
  348.          on session expiration as well as webapp lifecycle) --> 
  349.     <!-- 
  350.     <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /> 
  351.     --> 
  352. <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager" 
  353. memcachedNodes="n1:172.18.188.64:11211" 
  354. requestUriIgnorePattern=".*\.(png|gif|jpg|css|js)$" 
  355. sessionBackupAsync="false" 
  356. sessionBackupTimeout="100" 
  357. transcoderFactoryClass="de.javakaffee.web.msm.serializer.javolution.JavolutionTranscoderFactory" 
  358. copyCollectionsForSerialization="false"/> 
  359. </Context> 
  360. memcached启动命令: 
  361. useradd -s /sbin/nologin memcached 
  362. memcached -d -m 2048 -l 172.18.188.64 -p 11211 -u memcached 
  363. ngingx启动命令 
  364. sbin/nginx 
  365. tomcat启动命令(startup.sh) 
  366. 分别启动memcached nginx tomcat能实现session的简单共享. 
  367. 按照上面配置Nginx Memcached Tomcat启动运行都没有问题,并且可以实现Session的共享.但是有2个问题 
  368. 一、Session的共享是基于访问IP的,即在同一台电脑上开2个IE窗口时,获取到Session中内容是相同的,也就是sessionid除了最后面的jvmrout不一样,其他都一样,内容也一样,这样就造成如果2个用户先后在同一台电脑上登录形成session混乱,有没有可能配置成同一ip在不同的ie窗口中不共享session,一个ie窗口对应一个session,而不是一个ip共享一个session.后台的访问依然是由nginx根据weight做分发而不是固定到一台固定的tomcat机器? 
  369. 二、Memcached 启动是用-m 512发现会有数据丢失而且丢失几率很大,在一个页面上连续不断的刷新时就会发现session中的内容会清空.