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

 第一章. 背景简介 

对于大多数企业应用,都希望能做到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.7,请自行下载安装。 
2, Apache 2.4 下载地址: http://httpd.apache.org/ 
3, Tomcat 7.0.2,目前也是最新的版本。Minimum Java Version1.6.下载地址:http://tomcat.apache.org/ 
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

第三章 安装

1, JDK 安装请参照博客的其他部分  

2, Apache 2.4 安装请参照博客的其他部分  
3, Tomcat 7.0 解压就行了

第四章:配置

Apache 2.4 配置

conf/httpd.conf 的配置

# 监听端口和监听地址
Listen 80 

#加载代理
LoadModule proxy_module modules/mod_proxy.so    
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so    
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so    
LoadModule proxy_connect_module modules/mod_proxy_connect.so    
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so    
LoadModule proxy_http_module modules/mod_proxy_http.so  

#这个不加会报错,下面详解
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so

#这个额是负责均衡的分配策略
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so


#打开 Virtual hosts
Include conf/extra/httpd-vhosts.conf

httpd-vhosts.conf的配置:(这里有很多东西可以看的,这些都是我们实际的项目)

# 将www.shanghaiports.org --->>(转发)-->>  http://192.168.1.162:8080/SHPF
<VirtualHost *:80>
	ServerName www.shanghaiports.org
	ServerAlias shanghaiports.org *.shanghaiports.org
	
	ProxyPreserveHost On
	ProxyRequests Off
        ## 下面的两行请注意,如果位置弄反了,静态资源出不来
	ProxyPass /SHPF http://192.168.1.162:8080/SHPF
	ProxyPass / http://192.168.1.162:8080/SHPF/
	ErrorLog "logs/shanghaiports-error_log"
#	CustomLog "logs/shanghaiports-access_log" common
</VirtualHost>

# 将www.nbchuanbo.org --->>(转发)-->>  http://192.168.1.162:8080/XML
# 其实这个逻辑和上面的一样
<VirtualHost *:80>
	ServerName www.nbchuanbo.com
	ServerAlias nbchuanbo.com *.nbchuanbo.com
	
	ProxyPreserveHost On
	ProxyRequests Off	
	ProxyPass /XML http://192.168.1.162:8080/XML
	ProxyPass / http://192.168.1.162:8080/XML/
	ErrorLog "logs/nbchuanbo-error_log"
#	CustomLog "logs/nbchuanbo-access_log" common
</VirtualHost>

# 这里配置的不是负载均衡,是rewrite的配置。 这个就是普通的url跳转,你的url地址会变化的
<VirtualHost *:80>
	DocumentRoot "/"
	ServerName image.i-css.com
	ServerAlias image.i-css.com
	ErrorLog "logs/img-error_log"
#	CustomLog "logs/img-access_log" common

	<Directory "/"> 
		Options FollowSymLinks
		AllowOverride None
		Order Deny,Allow 
		Allow from all 
	</Directory>
	
	RewriteEngine on
	RewriteCond %{HTTP_HOST} ^image.i-css.com [NC]
	RewriteRule ^/(.*) http://www.img-css.com/$1 [L] 
</VirtualHost>


#这里是做负载均衡的;
ProxyRequests Off	
<VirtualHost *:80>  
    ServerName www.i-css.cn
    ServerAlias i-css.cn *i-css.cn
    ProxyRequests Off	
    ProxyPass / balancer://cn/ stickysession=JSESSIONID|jsessionid nofailover=On  
    #ProxyPassReverse / balancer://cn/  
    ErrorLog "logs/cn_error.log"  
    CustomLog "logs/cn_access.log" common  
</VirtualHost>

<proxy balancer://cn>  
    BalancerMember ajp://192.168.1.163:8009/Test loadfactor=1 route=s4 smax=5 max=20 ttl=120 retry=300 timeout=15  
    BalancerMember ajp://192.168.1.164:8009/Test loadfactor=1 route=s3 smax=5 max=20 ttl=120 retry=300 timeout=15 
    ProxySet lbmethod=bytraffic
</proxy>

<VirtualHost *:80>  
    ServerName www.i-css.com
    ServerAlias www.i-css.com
    ProxyRequests Off	
    ProxyPass / balancer://en/ stickysession=JSESSIONID|jsessionid nofailover=On  
    #ProxyPassReverse / balancer://en/  
    ErrorLog "logs/cn_error.log"  
    CustomLog "logs/cn_access.log" common  
</VirtualHost>
<proxy balancer://en>  
    BalancerMember ajp://192.168.1.163:8009/EN loadfactor=1 route=s4 smax=5 max=20 ttl=120 retry=300 timeout=15  
    BalancerMember ajp://192.168.1.164:8009/EN loadfactor=1 route=s3 smax=5 max=20 ttl=120 retry=300 timeout=15 
    ProxySet lbmethod=bytraffic
</proxy>

 

Tomcat7配置(server.xml): 

# 这里我也不说废话。直接找到<Engine />这个节点, 需要注意的是这个:jvmRoute="s3" 字面意思就是路由到其他的server上去
<Engine name="Catalina" defaultHost="localhost" jvmRoute="s3">
    
      <Realm className="org.apache.catalina.realm.LockOutRealm">
      	<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
            
        <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8">  
        <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="auto" port="4001" autoBind="100" selectorTimeout="5000"  
                    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="" />  
        <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve" />  
        <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"  
                tempDir="/tmp/war-temp/" deployDir="/tmp/war-deploy/" watchDir="/tmp/war-listen/"  
                watchEnabled="false" />  
        <ClusterListener  
                className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener" />  
        <ClusterListener  
                className="org.apache.catalina.ha.session.ClusterSessionListener" />  
        </Cluster>  

 
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>
</Engine>
<!--[endif]-->

第五章 测试:

写个简单的demo, 打成war包。通过tomcat manager上传到服务器上。

这里只测试负载均衡

1:test.jsp

<%@ page contentType="text/html; charset=GBK" %>  
<%@ page import="java.util.*" %>  
<html><head><title>Cluster Test</title></head>  
<body>  
<%  
  //HttpSession session = request.getSession(true);  
  System.out.println(session.getId());  
  out.println("<br> SESSION ID:" + session.getId()+"<br>");    
  // 如果有新的请求,则添加session属性  
	  String name = request.getParameter("name");  
	  if (name != null && name.length() > 0) {  
	     String value = request.getParameter("value");  
	     session.setAttribute(name, value);  
	  }    
	    out.print("<b>Session List:</b>");    
	    Enumeration<String> names = session.getAttributeNames();  
	    while (names.hasMoreElements()) {  
	        String sname = names.nextElement();   
	        String value = session.getAttribute(sname).toString();  
	        out.println( sname + " = " + value+"<br>");  
	        System.out.println( sname + " = " + value);  
	   }  
	%>  
	  <form action="testCluster.jsp" method="post">  
	    名称:<input type=text size=20 name="name">  
	     <br>  
	    值:<input type=text size=20 name="value">  
	     <br>  
	    <input type=submit value="提交">  
	   </form>  
	</body>  
	</html>  

2:web,xml

 <distributable/>

 

3:  注意

 需要存入session的对象必须要虚拟化。

4:测试

http://www.i-css.cn 你去刷新这个网页,你会看到sessionID没变,route会一直改变的。 

第六章. Mod_proxy负载均衡算法 

目前mod_proxy有3种负载均衡算法: 

1. Request Counting(我猜是Round-robin), lbmethod=byrequests 

2. Weighted Traffic Counting(这个是按权重,此例也是用此算法), lbmethod=bytraffic 

3. Pending Request Counting(从apche文档来看,应该是按负载量,也就是往负载少的派发新请求). lbmethod=bybusyness 

它们通过lbmethod值设置。

第七章. 参考文档: 

Tomcat 7 doc文档 

http://httpd.apache.org/docs/2.2/mod/mod_proxy_balancer.html 

http://httpd.apache.org/docs/2.2/mod/mod_proxy.html 

猜你喜欢

转载自shiguanghui.iteye.com/blog/1925155
今日推荐