apache和tomcat负载均衡

原创 2013年12月03日 18:04:26

为记录apache和tomcat负载均衡过程

测试环境:

xp 

Jdk      1.6

Apache   2.2.25       http://httpd.apache.org/download.cgi

Tomcat   tomcat6.0.37  http://tomcat.apache.org/download-60.cgi

一、apache httpserver 安装过程不再介绍

tomcat免安装版,如果是在同一主机上配置两个tomcat需要改相应的端口号防止冲突(本例是在一台主机上两个tomcat)

二、配置开始,修改httpd.conf文件

1、在apache的安装路径中找到httpd.conf文件

LoadModuleproxy_module modules/mod_proxy.so

LoadModuleproxy_ajp_module modules/mod_proxy_ajp.so

LoadModuleproxy_balancer_module modules/mod_proxy_balancer.so

LoadModuleproxy_connect_module modules/mod_proxy_connect.so

LoadModuleproxy_ftp_module modules/mod_proxy_ftp.so

LoadModuleproxy_http_module modules/mod_proxy_http.so

LoadModule proxy_scgi_modulemodules/mod_proxy_scgi.so

2、找到以下的信息,将Includeconf/extra/httpd-vhosts.conf 这行前面的#号去掉

# Virtual hosts

# Includeconf/extra/httpd-vhosts.conf

三、找到Apache2.2\conf\extra目录下的httpd-vhosts.conf,安装以下的方式进行修改

1.将这个文件下的 <VirtualHost*:80>内容全部替换为下面的部分,但是serverAdmin和ServerName两个字段的值保持覆盖之前的值。

<VirtualHost*:80> 

    ServerAdmin webmaster@dummy-host. com.cn

    ServerName dummy-host.com.cn

    ServerAlias www.dummy-host.com.cn 

    ProxyRequests Off

    ProxyPreserveHost on

    ProxyPass / balancer://tomcat-cluster/stickysession=JSESSIONID|jsessionid nofailover=Off

    ProxyPassReverse /balancer://tomcat-cluster/ 

    ErrorLog"logs/dummy-host2.sm.com-error.log" 

    CustomLog"logs/dummy-host2.sm.com-access.log" common

    <proxy balancer://tomcat-cluster> 

    BalancerMember ajp://127.0.0.1:18003loadfactor=1 route=jvm1 

    BalancerMember ajp://127.0.0.1:19003loadfactor=1 route=jvm2 

    ProxySet lbmethod=bybusyness

    </proxy>

</VirtualHost>

解释:

BalancerMemberajp://127.0.0.1:18003 loadfactor=1 route=jvm1 

BalancerMember ajp://127.0.0.1:19003loadfactor=1 route=jvm2 

这两行对应的是配置的tomcat相关内容,18003和19003这两个端口对应tomcat中的server.xml中的<Connectorport="19003" protocol="AJP/1.3"redirectPort="8443"/>配置的端口。Jvm1和jvm2必须和tomcat中的配置相对应

四、tomcat配置

1、tomcat1配置

<Server port="18001" 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="18002" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
    <!-- 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="18003" 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="jvm1">
		<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="6">  
        <Manager className="org.apache.catalina.ha.session.BackupManager" expireSessionsOnShutdown="false"   
        notifyListenersOnReplication="true" mapSendOptions="6"/>  
        <Channel className="org.apache.catalina.tribes.group.GroupChannel">  
            <Membership className="org.apache.catalina.tribes.membership.McastService"  
                address="228.0.0.4" port="45565" frequency="500" dropTime="3000"/>  
            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"  
                address="auto" port="5002" 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"/>  
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>  
        </Channel>  
        <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"  
            filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;"/>  
        <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.ClusterSessionListener"/>  
    </Cluster>  
      <!--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"/>
         --> 

      <!-- 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="/zdsas" docBase="F:\work\zdsas" reloadable="true" ></Context>
      </Host>
    </Engine>
  </Service>
</Server>
2、tomcat2配置

<Server port="19001" 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="19002" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
    <!-- 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="19003" 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="jvm2">
		<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="6">  
        <Manager className="org.apache.catalina.ha.session.BackupManager" expireSessionsOnShutdown="false"   
        notifyListenersOnReplication="true" mapSendOptions="6"/>  
        <Channel className="org.apache.catalina.tribes.group.GroupChannel">  
            <Membership className="org.apache.catalina.tribes.membership.McastService"  
                address="228.0.0.4" port="45565" frequency="500" dropTime="3000"/>  
            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"  
                address="auto" port="5002" 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"/>  
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>  
        </Channel>  
        <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"  
            filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;"/>  
        <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.ClusterSessionListener"/>  
    </Cluster>  
      <!--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"/>
       -->      

      <!-- 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">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"  
               prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
        -->
		<Context path="/zdsas" docBase="F:\work\zdsas" reloadable="true" ></Context>
      </Host>
    </Engine>
  </Service>
</Server>
五、编写测试页面

<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.util.*" %>
<html><head><title>Cluster App Test</title></head>
<body>
Server Info:
<%
out.println(request.getLocalAddr() + " : " + request.getLocalPort()+"<br>");%>
<%
  out.println("<br> ID " + session.getId()+"<br>");
  // 如果有新的 Session 属性设置
  String dataName = request.getParameter("dataName");
  if (dataName != null && dataName.length() > 0) {
     String dataValue = request.getParameter("dataValue");
     session.setAttribute(dataName, dataValue);
  }
  out.println("<b>Session 列表</b><br>");
  System.out.println("============================");
  Enumeration e = session.getAttributeNames();
  while (e.hasMoreElements()) {
     String name = (String)e.nextElement();
     String value = session.getAttribute(name).toString();
     out.println( name + " = " + value+"<br>");
         System.out.println( name + " = " + value);
   }
%>
  <form action="test2.jsp" method="POST">
    名称:<input type=text size=20 name="dataName">
     <br>
    值:<input type=text size=20 name="dataValue">
     <br>
    <input type=submit>
   </form>
</body>
</html>






Apache与Tomcat有什么关系和区别

经常在用apache和tomcat等这些服务器,可是总感觉还是不清楚他们之间有什么关系,在用tomcat的时候总出现apache,总感到迷惑,到底谁是主谁是次,因此特意在网上查询了一些这方面的资料,总...
  • longzs
  • longzs
  • 2013年09月03日 10:01
  • 77305

Apache服务器和tomcat服务器有什么区别?

Apache与Tomcat都是Apache开源组织开发的用于处理HTTP服务的项目,两者都是免费的,都可以做为独立的 Web服务器运行。Apache是Web服务器而Tomcat是Java应用服务器...
  • uniquewonderq
  • uniquewonderq
  • 2015年06月09日 16:58
  • 14995

Apache与Tomcat的关系?

以前自学过java一段时间,后来改行做PHP, 学习Java的时候只知道安装 tomcat 容器运行jsp文件,接触php后使用apache Web服务器,一直没搞清楚,现在详细了解一下两者的关系:...
  • JerryCorbitt
  • JerryCorbitt
  • 2015年04月17日 14:05
  • 1444

Apache 和tomcat 的环境搭建

-------- 此处接上文配置的ssl的环境 以下此为大神的转载./帮了不少忙 恩 http://blog.csdn.net/stefyue/article/details/6918542那么首先...
  • u011685720
  • u011685720
  • 2015年09月11日 09:56
  • 1511

Apache +Tomcat的负载均衡与集群配置

在上一篇文章中已经描述的单节点的apache和tomcat 集群配置接下来就讲述一下多节点(所有的猫都是在本地上的)选用的tomcat是6.0版本的      Tocmat7目前已经出现稳定版本的...
  • tan1012194073
  • tan1012194073
  • 2016年05月25日 15:18
  • 2527

Apache Tomcat的安装配置方式

在启动Apache Tomcat服务器前,先要确保java的配置环境是正确的,以下内容都是在这基础之上! 1.有段时间没用Apache Tomcat了,由于前段时间电脑有问题,重装了几次系统,数据...
  • qq_32224139
  • qq_32224139
  • 2017年04月11日 15:12
  • 1363

apache和tomcat有什么不同,为什么要整合apache 和tomcat?

1. Apache是web服务器,Tomcat是应用(java)服务器,它只是一个servlet容器,是Apache的扩展。 2. Apache和Tomcat都可以做为独立的web服务器来运行,但是...
  • zhangheng837964767
  • zhangheng837964767
  • 2015年10月22日 17:06
  • 1492

apache 多个tomcat 多个应用 整合配置(实战结果)

需求:1、两个应用(应用1为微信公众平台,应用2为商城)中各根据不同的请求域名得到不同的商家信息,如 应用1:www.ivlian.com 得到商家爱微联的信息,www.yuweima.com得到商家...
  • lixiang810
  • lixiang810
  • 2014年03月27日 23:03
  • 1162

Apache虚拟主机和虚拟目录+tomcat集成的配置

Apache:  2.2.14 Tomcat:  6.0.4 Jk:   mod_jk-1.2.28-httpd-2.2.3.so Jdk:  jdk1.6.0_10 服务器:windows2...
  • z0830163
  • z0830163
  • 2014年04月04日 18:14
  • 1298

Apache和Tomcat整合(一个Apache 不同域名处理多个不同业务)

简介 在项目中,几乎任何一个项目都包括静态资源和动态请求两大部分。特别对于门户网站这样的项目,静态内容资源会更多,我们使用一般的 Tomcat 部署时,Tomcat 对静态资源的处理能力比较慢,至少比...
  • catoop
  • catoop
  • 2015年08月25日 12:25
  • 7230
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:apache和tomcat负载均衡
举报原因:
原因补充:

(最多只允许输入30个字)