日期:2014-05-16  浏览次数:20716 次

基于mod_proxy+Apache 2.2.16+Tomcat 7的负载均衡与集群配置
基于mod_proxy+Apache 2.2.16+Tomcat 7的负载均衡与集群配置
Peter Wei



周日晚和GF的老乡们喝了五粮液,导致周一起不了床,只好请假在家睡觉。白天睡了半天,晚上自然睡不着觉。正好现在的项目中也用到了负载均衡和集群的东西,虽然有新手贴的危险,但还是手痒,决定写点东西,以备不时之需。也希望能对大家有所帮助。

第一章. 背景简介
对于大多数企业应用,都希望能做到7*24小时不间断运行。要保持如此高的可用性并非易事,比较常见的做法是将系统部署到多台机器上,每台机器都对外提供同样的功能,这就是集群。系统变为集群时,除了要求系统能够支持水平伸缩外,还要解决两个问题:
1, 如何均衡地访问到提供业务功能的机器。
2, 如何保证当机器出现问题时,用户能自动跳转到另外的机器,不影响使用。

常用的负载均衡技术有硬件和软件两种,本示例常用软件的技术实现。软件也有很多实现技术,如基于apache的mod_jk以及mod_proxy等。基于mod_jk的文章有不少,本文演示一下用mod_proxy的方式。
实现集群的应用最重要的是处理用户Session的问题,一般有三种策略:
1, Session复制
2, Session Sticky
3, 基于Cache的集中式Session

本文使用的是Tomcat 7.0.2应用服务器,用的方法是Session复制。

第二章. 配置环境
1, JDK1.6,请自行下载安装,搞Java的一般都装有的吧,哈哈。
2, Apache 2.2.16, (released 2010-07-25),现在为止应该是最新的稳定版本,下载地址: http://httpd.apache.org/download.cgi
3, Tomcat 7.0.2,目前也是最新的版本。Minimum Java Version1.6.下载地址:http://tomcat.apache.org/download-70.cgi
4, 安装过程略

第三章. 部署图




第四章. Tomcat7集群配置
一、 就地取材,复制tomcat7/webapps下的examples,重命名为cluster应用,以后就用cluster做测试。
二、 详细配置参照tomcat7 \webapps\docs\cluster-howto.html 或者http://tomcat.apache.org/tomcat-7.0-doc/cluster-howto.html
三、 为了在Tomcat7中实现session复制,以下必需完成:
? 所有session属性必需实现 java.io.Serializable
? Uncomment the Cluster element in server.xml。把Cluster元素的注释去掉。参照四
? If you have defined custom cluster valves, make sure you have the ReplicationValve defined as well under the Cluster element in server.xml 。参照四
? If your Tomcat instances are running on the same machine, make sure the tcpListenPort attribute is unique for each instance, in most cases Tomcat is smart enough to resolve this on it's own by autodetecting available ports in the range 4000-4100。参照四< Receiver>中的注释
? Make sure your web.xml has the <distributable/> element or set at your <Context distributable="true" /> 参照四
? If you are using mod_jk, make sure that jvmRoute attribute is set at your Engine <Engine name="Catalina" jvmRoute="node01" > and that the jvmRoute attribute value matches your worker name in workers.properties .用mod_jk的情况,我们可以不管。
? Make sure that all nodes have the same time and sync with NTP service! 当使用多台机器时,要保证不同机器时间的同步。原因为tomcat session复制的一些机制。具体原因看文档。
? Make sure that your loadbalancer is configured for sticky session mode. 保证负载均衡软件设置为session sticky模式。
四、 详细配置:
1. 修改tomcat7_a/conf/server.xml, 我们采用的是默认的配置,在<Engine>节点下添加:

Java代码 复制代码
  1. <Cluster?className="org.apache.catalina.ha.tcp.SimpleTcpCluster"??
  2. ?????????????????channelSendOptions="8"> ??
  3. ??
  4. ??????????<Manager?className="org.apache.catalina.ha.session.DeltaManager"??
  5. ???????????????????expireSessionsOnShutdown="false"??
  6. ???????????????????notifyListenersOnReplication="true"/> ??
  7. ??
  8. ??????????<Channel?className="org.apache.catalina.tribes.group.GroupChannel"> ??