`
wawa129
  • 浏览: 321149 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

轻松实现Apache,Tomcat集群和负载均衡

 
阅读更多
0, 环境说明
       Apache  :apache_2.0.55     1 个
       Tomcat:  apache-tomcat-5.5.17 (zip版) 2个
       mod_jk:: mod_jk-apache-2.0.55.so  1个
第一部分:负载均衡
    负载均衡,就是apache将客户请求均衡的分给tomcat1,tomcat2....去处理
   1.安装apche,tomcat
   http://httpd.apache.org/ 下载Apache 2.0.55
    http://tomcat.apache.org/download-55.cgi 下载tomcat5.5 zip版本(解压即可,绿色版)
   http://apache.justdn.org/tomcat/tomcat-connectors/jk/binaries/win32/jk-1.2.15/  下载mod_jk,注意和  apache版本匹配
   按照jdk,我的路径为:E:\ide\apache\Apache2
   解压两份Tomcat, 路径分别为 E:\ide\tomcat1,E:\ide\tomcat2

下载mod_jk


2.修改Apache配置文件http.conf
   在apache安装目录下conf目录中找到http.conf
   在文件最后加上下面一句话就可以了
  include "E:\ide\apache\Apache2\conf\mod_jk.conf"

2. http.conf 同目录下新建mod_jk.conf文件,内容如下
  
#加载mod_jk ModuleLoadModule jk_module modules/mod_jk-apache-2.0.55.so
#指定 workers.properties文件路径JkWorkersFile conf/workers.properties
#指定那些请求交给tomcat处理,"controller"为在workers.propertise里指定的负载分配控制器
JkMount /*.jsp controller
3.在http.conf同目录下新建 workers.properties文件,内容如下
 
worker.list = controller,tomcat1,tomcat2  #server 列表
#========tomcat1========
worker.tomcat1.port=8009         #ajp13 端口号,在tomcat下server.xml配置,默认8009worker.tomcat1.host=localhost  #tomcat的主机地址,如不为本机,请填写ip地址worker.tomcat1.type=ajp13worker.tomcat1.lbfactor = 1   #server的加权比重,值越高,分得的请求越多
#========tomcat2========
worker.tomcat2.port=9009       #ajp13 端口号,在tomcat下server.xml配置,默认8009worker.tomcat2.host=localhost  #tomcat的主机地址,如不为本机,请填写ip地址worker.tomcat2.type=ajp13worker.tomcat2.lbfactor = 1   #server的加权比重,值越高,分得的请求越多
#========controller,负载均衡控制器========worker.controller.type=lbworker.controller.balanced_workers=tomcat1,tomcat2   #指定分担请求的tomcatworker.controller.sticky_session=1
4.修改tomcat配置文件server.xml
如果你在不同电脑上安装tomcat,tomcat的安装数量为一个,可以不必修改tomcat配置文件
我这里是在同一台电脑上安装两个tomcat,所以需要更改其中一个的设置
打开tomcat2/conf/server.xml文件



5.编写一个测试jsp
建立一个目录test.里面新建一个test.jsp,内容为
<%    System.out.println("===========================");%>
把test放到tomcat1,tomcat2的webapps下
6.启动apache,tomcat1,tomcat2,进行测试
通过 http://localhost/test/test.jsp 访问,查看tomcat1的窗口,可以看到打印了一行"=========="
再刷新一次,tomcat2也打印了一条,再刷新,可以看到请求会被tomcat1,tomcat2轮流处理,实现了负载均衡

第二部分,配置集群
   只配置负载均衡还不行,还要session复制,也就是说其中任何一个tomcat的添加的session,是要同步复制到其它tomcat, 集群内的tomcat都有相同的session
1. 修改tomcat1, tomcat2的server.xml,将集群部分配置的在注释符删掉,并将tomcat2的4001端口改为4002,以避免与tomcat冲突,当然,如果是两台电脑,是不用改端口的,去掉注释符即可
  




2,修改测试项目test
修改test.jsp,内容如下
  <%@ 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.print("<b>Session 列表</b>");
  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="index.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>
然后在test 新建WEB-INF目录,WEB-INF下新建web.xml,内容如下
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">       <display-name>TomcatDemo</display-name>       <distributable/></web-app>
注意:在你的应用的web.xml加入  <distributable/> 即可
ok,讲test复制到tomcat1,tomcat2的webapps下,重启apache,tomcat1,tomcat2,
输入网址 http://localhost/test/test.jsp  
新建一个 名称为 xiaoluo  ,值为 cdut 的session,提交查询,新开一个ie窗口,再提交查询,如图,可以看到,两个tomcat 是负载均衡,并且session同步的


Tomcat1:
<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
-->
<Server port="8005" 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" />
  <!-- 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="8080" 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="8009" 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="Standalone" defaultHost="localhost" jvmRoute="jvm1">        
    -->
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">

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

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                 channelSendOptions="6">

          <Manager className="org.apache.catalina.ha.session.BackupManager"
                   expireSessionsOnShutdown="false"
                   notifyListenersOnReplication="true"
                   mapSendOptions="6"/>
          <!--
          <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"
                      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>


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

      </Host>
    </Engine>
  </Service>
</Server>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics