文档章节

NginxTomcatRedis实现应用服务器集群负载均衡和Session共享

代码大权都在手
 代码大权都在手
发布于 2016/09/19 09:48
字数 2391
阅读 8
收藏 0

Nginx+Tomcat+Redis实现应用服务器集群负载均衡和Session共享

1.实验环境和所需软件

   1.Windows7环境

   2.nginx 1.6.3

   3.redis 2.6.2

   4.Tomcat 7.0.56
   

2.配置Nginx

2.1 Nginx路径:E:\new\Tomcat_Nginx_Cluster\nginx-1.6.3\

#Nginx所有用户和组,window下不指定
#user Adminstrator
#user  nobody;
#工作的子进程数量(通常等于CPU核数或者2倍与CPU核数)
worker_processes  4;

#错误日志存放路径
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#指定pid存放文件
#pid        logs/nginx.pid;


events {
#使用网络IO模型,Linux建议用epoll,FreeBSD建议用kqueue,window下不指定
#use epoll
#设置单个进程同时打开的最大连接数
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

#定义日志格式
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    #http连接的持续时间
    keepalive_timeout  65;
    
#gzip压缩设置
    #gzip  on; #是否打开gzip压缩,默认不打开
    gzip_min_length 1k;  #最小压缩文件大小
    gzip_buffers 4 16k;  #压缩缓冲区
    #http的协议版本(1.0/1.1),默认1.1,前端如果是squid2.5请使用1.0
    gzip_http_version 1.1;
    #gzip压缩比,1压缩比最小处理速度最快,9压缩比最大但处理速度最慢(传输快但比较消耗cpu)
    gzip_comp_level 2;   
    #和http头有关系,加个vary头,给代理服务器用的,有的浏览器支持压缩,有的不支持,所以避免浪费不支持的也压缩,所以根据客户端的HTTP头来判断,是否需要压缩
    gzip_vary on;
    #gzip压缩类型,不用添加text/html,否则会有警告信息
    gzip_types text/plain text/javascript text/css application/xmlapplication/x-javascript application/json;


#设定负载均衡的服务器列表,可以配置多个upstream,但mysvr名字要区分
#下面配置请求的负载分配
    upstream localhost {
      #根据ip计算将请求分配给那个后端Tomcat,注意:这里并不能解决Session共享问题
      #同一机器在多网情况下,路由切换,ip可能不同
      #ip_hash
      #weight参数表示权值,权值越高被分配到的几率越大,一般在生产环境中,需要根据访问情况制定相应算法
      server localhost:8080 weight=5;
      server localhost:8081 weight=5;
    }

    server {
        #Nginx监听的端口号
        listen       80;
    #域名可有多个,用空格隔开
        server_name  localhost;

        #字符编码集
        #charset koi8-r;
    charset utf-8;

        #设定本虚拟主机的访问日志。关闭日志可减少IO,提高性能
        #access_log  logs/host.access.log  main;

        #默认请求
        location / {
        #定义服务器的默认网站根目录位置
            #root   html;
        root E:\new\Tomcat_Nginx_Cluster;
        #定义首页
            index  index.html index.htm index.jsp;
        #请求专项mysvr定义的服务器列表
        #配置端口转发,proxy_pass
        proxy_pass http://localhost;
        proxy_redirect default;
        #与代理服务器连接的超时时间,必须留意这个timeout不能超过75秒,当一台服务器宕机时,过10秒转发到另外一台服务器
        proxy_connect_timeout 10;
        }

        location ~ .*.jsp$ #所有jsp的页面均交由tomcat处理
        {
             index index.jsp;
                 proxy_pass http://localhost;#转向tomcat处理
        }

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ #设定访问静态文件直接读取不经过tomcat
        {
         #设置静态资源的过期时间
             expires 30d;
        }

        #定义几种常见的错误页面:404,400,500等
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }


    #对本server"/"启用负载均衡  
        #location / {  
        #    proxy_pass http://mysvr;  
        #    proxy_redirect off;  
        #    proxy_set_header Host $host;  
        #    proxy_set_header X-Real-IP $remote_addr;  
        #    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
        #    client_max_body_size 10m;  
        #    client_body_buffer_size 128k;  
        #    proxy_connect_timeout 90;  
        #    proxy_send_timeout 90;  
        #    proxy_read_timeout 90;  
        #    proxy_buffer_size 4k;  
        #    proxy_buffers 4 32k;  
        #    proxy_busy_buffers_size 64k;  
        #    proxy_temp_file_write_size 64k;  
        #}  

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}


3.配置两个Tomcat
 1. 在两个Tomcat的lib中导入连接redis需要的jar包:

 commons-logging-1.1.3,jar
 commons-pool2.2.2.jar
 jedis-2.5.2.jar
 readme.md
 tomcat-juli.jar
 tomcatredis-session-manage-tomcat7.jar

 2.配置两个Tomcat通过redis共享session

* Tomcat-8080          ---        localhost:8080

  1.conf/server.xml端口配置   ---   使用默认的8080端口,只需配置这个Tomcat了

  Engine元素增加jvmRoute属性:

   
   <Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat8080"> 
   
 
  2.conf/context.xml配置         ---   连接redis共享session的配置

   <Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
    <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
         host="localhost"
         port="6379" 
         database="0" 
         maxInactiveInterval="60" />

完整配置:

<span style="font-family: Arial, Helvetica, sans-serif;"><?xml version='1.0' encoding='utf-8'?></span>

<?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.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
    <Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
         host="localhost"
         port="6379" 
         database="0" 
         maxInactiveInterval="60" />

</Context>


* Tomcat-8081          ---        localhost:8081

 1.conf/server.xml端口配置   ---   使用8081端口,需要在server.xml中进行相应的配置(4个地方需要修改端口)

 第一处端口修改:

 <!--  修改port端口:8006 俩个tomcat不能重复,端口随意,别太小-->    
  <Server port="8006" shutdown="SHUTDOWN">

 第二处端口修改:

<!-- port="8081" tomcat监听端口,随意设置,别太小 -->    
<Connector port="8081" protocol="HTTP/1.1"connectionTimeout="20000"      
               redirectPort="8443" />    

第三处端口修改:

 <Connector port="18009" protocol="AJP/1.3" redirectPort="18443" />   


Engine元素增加jvmRoute属性:


<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat8081">    


完整配置:

<?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="8006" shutdown="SHUTDOWN">
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--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" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- 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="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="18443" />
    <!-- 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 BIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="18009" protocol="AJP/1.3" redirectPort="18443" />


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

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

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- 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"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- 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
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>


  2.conf/context.xml配置         ---   连接redis共享session的配置

4.启动nginx、redis和两个Tomcat组建集群

       1.创建index.jsp测试文件

         在两个Tomcat的webapps下面创建一个test目录,并创建一个index.jsp文件
     
 <%@ page language="java" %>  
<html>  
  <head><title>TomcatA</title></head>  
  <body>  
   
    <table align="centre" border="1">  
      <tr>  
        <td>Session ID</td>  
        <td><%= session.getId() %></td>  
      </tr>  
      <tr>  
        <td>Created on</td>  
        <td><%= session.getCreationTime() %></td>  
     </tr>  
    </table>  
  </body>  
</html>  
sessionID:<%=session.getId()%>   
<br>   
SessionIP:<%=request.getServerName()%>   
<br>   
SessionPort:<%=request.getServerPort()%>   
<%   
//为了区分,第二个可以是222  
out.println("This is Tomcat Server 1111");   
%>    


       2.先启动Nginx、再启动redis,最后启动两个Tomcat

         说明: Windows下Nginx的启动与关闭
                启动: E:\new\Tomcat_Nginx_Cluster\nginx-1.6.3>nginx.exe
                关闭:E:\new\Tomcat_Nginx_Cluster\nginx-1.6.3>nginx -s quit

5.测试Session共享
 打开浏览器去访问第一个Tomcat,然后再第二个Tomcat,页面Session信息如下
  
 

 由图可以看到,三个Tomcat的SessionID都是一样的:9BE0CD81E96DCBEEC2DD4AD5E2A63D09,只要不关闭浏览器,不管怎么刷新,SessionID都是不变了。由此可以,三个Tomcat通过redis实现了Session信息共享。
 

 

以上均进行试验测试通过,学习!

本文转载自:http://blog.csdn.net/he90227/article/details/50177749#comments

代码大权都在手
粉丝 1
博文 1
码字总数 0
作品 0
南京
项目经理
私信 提问
浅谈web应用的负载均衡、高可用、群集

1、熟悉几个组件 1.1、apache —— 它是Apache软件基金会的一个开放源代码的跨平台的网页服务器,属于老牌的web服务器了,支持基于Ip或者域名的虚拟主机,支持代理服务器,支持安全Socket层(...

壹休哥
2016/11/06
0
0
浅谈web应用的负载均衡、集群、高可用(HA)解决方案

1、熟悉几个组件 1.1、apache —— 它是Apache软件基金会的一个开放源代码的跨平台的网页服务器,属于老牌的web服务器了,支持基于Ip或者域名的虚拟主机,支持代理服务器,支持安全Socket层(...

stone_
2016/05/04
366
0
nginx负载均衡实现tomcat集群方案简要小结

重点两部分:一、负载均衡二、tomcat集群 所谓tomcat集群,就是可以向外提供并行服务的多台机器,任何一台服务器宕机,其它服务器可以替代它向外提供服务,而不影响用户访问。 nginx是一个常...

天下杰论
2015/03/11
1K
1
Nginx在Windows平台的配置

1.1.1 课程目标: 课程目标: 能够使用Nginx搭建Tomcat集群,并完成负载均衡. 1.1.2 Nginx的概述: 什么是Nginx: 为什么使用Nginx: 度娘的解释: 背景: 互联网飞速发展的今天,大用户量高并发已经...

pxk
2017/10/29
47
1
负载均衡集群中的session解决方案

前言 在我们给Web站点使用负载均衡之后,必须面临的一个重要问题就是Session的处理办法,无论是PHP、Python、Ruby还是Java,只要使用服务器保存Session,在做负载均衡时都需要考虑Session的问...

a928154159
2017/09/13
0
0

没有更多内容

加载失败,请刷新页面

加载更多

golang-字符串-地址分析

demo package mainimport "fmt"func main() {str := "map.baidu.com"fmt.Println(&str, str)str = str[0:5]fmt.Println(&str, str)str = "abc"fmt.Println(&s......

李琼涛
今天
4
0
Spring Boot WebFlux 增删改查完整实战 demo

03:WebFlux Web CRUD 实践 前言 上一篇基于功能性端点去创建一个简单服务,实现了 Hello 。这一篇用 Spring Boot WebFlux 的注解控制层技术创建一个 CRUD WebFlux 应用,让开发更方便。这里...

泥瓦匠BYSocket
今天
6
0
从0开始学FreeRTOS-(列表与列表项)-3

FreeRTOS列表&列表项的源码解读 第一次看列表与列表项的时候,感觉很像是链表,虽然我自己的链表也不太会,但是就是感觉很像。 在FreeRTOS中,列表与列表项使用得非常多,是FreeRTOS的一个数...

杰杰1号
今天
4
0
Java反射

Java 反射 反射是框架设计的灵魂(使用的前提条件:必须先得到代表的字节码的 Class,Class 类 用于表示.class 文件(字节码)) 一、反射的概述 定义:JAVA 反射机制是在运行状态中,对于任...

zzz1122334
今天
5
0
聊聊nacos的LocalConfigInfoProcessor

序 本文主要研究一下nacos的LocalConfigInfoProcessor LocalConfigInfoProcessor nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/config/impl/LocalConfigInfoProcessor.java p......

go4it
昨天
9
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部