nginx+tomcat8+redis实现session共享

一、配置nginx的负载均衡

  1.tomcat 改端口,一个为8180,一个为8280.

  2.下载nginx-1.12.2 修改conf/nginx.conf

  在#gzip  on;下添加
    
    upstream localhost {
        server localhost:8180 weight=1;
        server localhost:8280 weight=1;
    }

 在server { 的部分改为如下
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            proxy_set_header  Host $host:$server_port;
            proxy_redirect  http://localhost http://localhost:80;
            proxy_pass  http://localhost;
        }

 (直接启动nginx.exe,在cmd中nginx -s reload可以重启)

二、设置session共享

  1.新建maven项目helloword

      下载 https://github.com/jcoleman/tomcat-redis-session-manager 。取出其src放入自己的项目

    RedisSessionManager.java有一个修改:

//    if (getContainer() != null) {
//      loader = getContainer().getLoader();
//    }

改为:
    Context context = this.getContext();
    if(context!=null){
        loader = context.getLoader();
    }

       pom.xml


  4.0.0
  com.bj
  helloword
  0.0.1-SNAPSHOT
  jar
  
  
        
            org.apache.tomcat
            tomcat-catalina
            8.0.33
        
        
            redis.clients
            jedis
            2.7.2
        
    

    
        
             
                org.apache.maven.plugins
                maven-compiler-plugin
                3.0
                
                    
                    1.8
                    
                    1.8
                    
                    UTF-8
                
            
        
    

打包jar放入tomcat的lib下。(helloword-0.0.1-SNAPSHOT.jar、 jedis-2.9.0 .jar、commons-pool2-2.4.2.jar)

  2.新建web工程

  Hello_Word 

  index.jsp


	访问的Nginx IP:<%=request.getServerName()%>
	
Tomcat SessionPort:<%=request.getServerPort()%> <% out.println("Tomcat Server Info=" + request.getLocalAddr() + " : " + request.getLocalPort() + "
"); out.println("当前 Session ID=" + session.getId() + "
"); %> <% String dataName = request.getParameter("dataName"); if (dataName != null && dataName.length() > 0) { String dataValue = request.getParameter("dataValue"); session.setAttribute(dataName, dataValue); } out.println("Session列表
"); System.out.println("Session列表"); Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = session.getAttribute(name).toString(); out.println(name + " = " + value + "
"); System.out.println(name + " = " + value); } %>
名称:
值:

  3.更改tomcat 8180和8280的context.xml

下添加,即redis做session共享

    WEB-INF/web.xml
    ${catalina.base}/conf/web.xml
    
    

4.启动redis

你可能感兴趣的:(Java后台)