nginx+haproxy做负载均衡到后端2台tomcat服务器

1台nginx(haproxy)+2台tomcat主机做负载均衡
步骤1:拓扑图

tomcat A 主机的配置
安装必要的软件:
yum -y install java-1.8.0-openjdk-devel tomcat-lib tomcat-admin-webapps tomcat-webapps tomcat-docs-webapp

创建tomcat存放数据目录
mkdir -pv /data/webapps/ROOT/{classes,lib,WEB-INF,META-INF}
具体目录的说明:

WEB-INF/:当前webapp的私有资源路径;通常用于存储当前webapp的web.xml和context.xml配置文件;
META-INF/:类似于WEB-INF/;
classes/:类文件,当前webapp所提供的类;
lib/:类文件,当前webapp所提供的类,被打包为jar格式;
配置tomcat的文件server.xml

配置主配置文件
vim /etc/tomcat/server.xml 中的<host>标签中添加如下配置,该配置主要是配置tomcat主机的路径、主机名以及日志格式

  <Host name="www.ilinux.io" appBase="/data/webapps" unpackWARs="true" autoDeploy="true" >
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="ilinux_access_log." suffix=".log"
               pattern="%h %l %u %t "%r" %s %b" />
        </Host>

添加tomcatA的测试文件
vim /data/webapps/ROOT/index.jsp

 <%@ page language="java" %>
<html>
      <head><title>TomcatA</title></head>
            <body>
                  <h1><font color="red">TomcatA.magedu.com</font></h1>
                <table align="centre" border="1">
              <tr>
              <td>Session ID</td>
                <% session.setAttribute("magedu.com","magedu.com"); %>
            <td><%= session.getId() %></td>
        </tr>
        <tr>
            <td>Created on</td>
          <td><%= session.getCreationTime() %></td>
        </tr>
        </table>
    </body>
</html>

为了测试方便,把默认的测试目录修改下路径
cp -r /data/webapps/ROOT/ /usr/share/tomcat/webapps/test
重启tomcat服务
systemctl start tomcat
查看下端口是否开启
ss -tnl

tomcatB 主机的配置和comcatA一样,此处省略

测试主页
输入ip地址为:192.168.100.205/test

到此,两台tomcat主机已经配置完成!

使用haproxy做负载均衡

安装haproxy
yum -y install haproxy
配置haproxy.cfg
vim /etc/haproxy/haproxy.cfg 添加如下内容,即可!

frontend http-in
    bind *:80
    default_backend appsrvs # 定义默认后端服务
backend appsrvs
    balance roundrobin    #轮询
        server  app1 192.168.100.203:8080 check  #开启健康检查
        server  app2 192.168.100.204:8080 check  #开启健康检查

listen stats   #开启状态管理接口
    bind *:9009
    stats enable

启动haproxy服务
systemctl start haproxy
查看端口
ss -tnl
80和9009端口启动证明服务正常。

测试,输入如下ip地址:192.168.100.205/test
查看状态页输入地址:192.168.100.205:9009/haproxy?stats 即可

使用nginx做负载均衡

安装nginx服务
yum install nginx
配置配置文件
vim /etc/nginx/conf/nginx.conf 增加一组webapps即可

    upstream appsrvs {
        server 192.168.100.203:8080;
        server 192.168.100.204:8080;
 }

启动服务
systemctl start nginx
查看端口
ss -tnl

http负载均衡实验(有两种方式:http模式和ajp模式 )

首先使用httpd做负载均衡

安装httpd服务
yum install httpd -y
配置httpd服务 ,新建一个虚拟主机

vim /etc/httpd/con.d/comcat-httpd.conf 添加如下配置

            <proxy balancer://appsrvs>
                BalancerMember http://192.168.100.203:8080
                BalancerMember http://192.168.100.204:8080
                ProxySet lbmethod=byrequests
            </Proxy>

            <VirtualHost *:80>
                ServerName  www.ilinux.io
                ProxyRequests Off
                ProxyVia        On
                ProxyPreserveHost On
                <Proxy *>
                    Require all granted
                </Proxy>
                ProxyPass / balancer://appsrvs/
                ProxyPassReverse / balancer://appsrvs/
                <Location />
                    Require all granted
                </Location>
            </VirtualHost>

启动httpd服务
systemctl start httpd
测试:输入ip地址:192.168.100.205/test

ajp模式的负载均衡

修改配置文件

vim /etc/httpd/http.d/tomcat.ajp.conf
            <proxy balancer://appsrvs>
                BalancerMember ajp://192.168.100.203:8009
                BalancerMember ajp://192.168.100.204:8009
                ProxySet lbmethod=byrequests
            </Proxy>

            <VirtualHost *:80>
                ServerName  www.ilinux.io
                ProxyRequests Off
                ProxyVia        On
                ProxyPreserveHost On
                <Proxy *>
                    Require all granted
                </Proxy>
                ProxyPass / balancer://appsrvs/
                ProxyPassReverse / balancer://appsrvs/
                <Location />
                    Require all granted
                </Location>
            </VirtualHost>
注意:端口一定要写出8009,否则方向代理不到后端服务器

使用cookie实现sessions绑定

在tomcat-apj-conf 中添加一些配置即可

vim /etc/httpd/conf.d/tomcat-ajp.conf



Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED  新增加的信息   
                        <proxy balancer://appsrvs>
                                BalancerMember ajp://192.168.100.203:8009 route=TomcatA  新增加的信息
                                BalancerMember ajp://192.168.100.204:8009 route=TomcatB 新增加的信息
                                ProxySet lbmethod=byrequests
                                ProxySet stickysession=ROUTEID  新增加的信息
                        </Proxy>

                        <VirtualHost *:80>
                                ServerName  www.ilinux.io
                                ProxyRequests Off
                                ProxyVia        On
                                ProxyPreserveHost On
                                <Proxy *>
                                        Require all granted
                                </Proxy>
                                ProxyPass / balancer://appsrvs/
                                ProxyPassReverse / balancer://appsrvs/
                                <Location />
                                        Require all granted
                                </Location>
                        </VirtualHost>

如果需要启动管理接口功能,在以上配置下添加如下配置。

                <Location /balancer-manager>
                    SetHandler balancer-manager
                    ProxyPass !
                    Require all granted
                </Location> 

以下为:管理接口的图形界面

使用session culster 做会话绑定

在原有的tomcatA的server.xml 配置中,把配置放置在host标签中

<Engine name="Catalina" defaultHost="localhost" "> 中添加如下信息jvmRoute="tcA"
<Engine name="Catalina" defaultHost="localhost" jvmRoute="tcA">

vim /etc/tomcat/server.xml
        <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="192.168.100.203"  atuo改成本地对外的通讯地址 
                      port="4000"
                      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>

为了安全,需要把web.xml 文件放在下如下目录,
cp /etc/tomcat/web.xml /usr/share/tomcat/webapps/test/WEN-INF目录中,WEN-INF目录私有目录,在web.xml中添加如下一行配置,是为了能够两个后端的两台tomcat可以同步数据。
编辑该文件

vim web.xml  
在<server>标签外添加一行信息;        <distributable/>即可

在tomcatB 中配置也需要添加<distributable/>信息。
在浏览器中输入:http://192.168.100.205/test 做测试,结果如下:

负载均衡两个节点都可以保持session一致。

使用memcache做session服务器

拓扑图如下:


下载如下jar文件至各tomcat节点的tomcat安装目录下的/usr/share/java/tomcat/
目录中,其中的${version}要换成你所需要的版本号,tc${6,7,8}要换成与tomcat版本相同的版本号。
这里我使用的是tomcat7.0 ,其他没有版本对应要求,需要的软件包如下


memcached-session-manager-${version}.jar
    memcached-session-manager-tc7-${version}.jar
    spymemcached-${version}.jar
    msm-javolution-serializer-${version}.jar
    javolution-${version}.jar

分别在两个tomcat上的某host上定义一个用于测试的context容器,并在其中创建一个会话管理器

        <Context path="/test" docBase="test" reloadable="true">
              <Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
                memcachedNodes="n1:192.168.100.203:11211,n2:192.168.100.204:11211"
                failoverNodes="n1"
                requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$"
                transcoderFactoryClass="de.javakaffee.web.msm.serializer.javolution.JavolutionTranscoderFactory"
              />
        </Context>

配置完成,启动memcached服务
systemctl start memcached
在浏览器中输入测试地址:http://192.168.100.205/test
测试结果:nginx(haproxy)调度,都可以保持session。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容