1、启动两个tomcat,端口分别为8080,8081

2、配置nginx,vim /usr/local/nginx/conf/nginx.conf

  添加如下配置:

  CentOS7下Nginx搭建反向代理,并使用redis保存session

3、启动nginx或热加载

  启动:

    cd /usr/local/nginx/sbin

    ./nginx

  热加载

    ./nginx -s reload

4、在tomcat中部署一个项目,写个servlet如下

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class HelloWorldServlet extends HttpServlet{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session= request.getSession();
        int port2=request.getLocalPort();
        if(session.getAttribute("userid")==null){
             String userid= String.valueOf(new Random().nextInt(100)) ;
             session.setAttribute("userid", userid);
             response.getWriter().append("Hello, "+userid+",this is "+port2+ " port");
        }else{
            String userid=(String)session.getAttribute("userid");
            response.getWriter().append("Welcome back, "+userid+", this is "+port2+" port") ;
        }
 
    }
}

配置web.xml

<servlet>
     <servlet-name>HelloWorldServlet</servlet-name>
     <servlet-class>com.atguigu.servlet.HelloWorldServlet</servlet-class>
 </servlet>
 <servlet-mapping>
     <servlet-name>HelloWorldServlet</servlet-name>
     <url-pattern>/test</url-pattern>
 </servlet-mapping>

5、访问测试,浏览器地址栏输入:

  nginx所在电脑ip/项目名/test

  此时,默认是轮询算法,每次访问的tomcat不一样导致,无法维护session会话。

6、解决办法:用redis存储session,实现session共享

  6.1把jar包拷到tomcatlib包下

    commons-pool2-2.0.jar

    jedis-2.5.2

    tomcat-redis-session-manager1.2.jar

  6.2通知tomcat,不要管理session了,交给redis管理,需要修改tomcat配置文件,注意修改前先关闭tomcat

    启动redis   redis-server /redis配置文件

    编辑context.xml,在context节点加入:

<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" /> 
<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager" 
host="redis电脑ip" 
port="redis端口号" 
database="0" 
maxInactiveInterval="60" />

 

7、在刷新浏览器,即使就会保持会话了,检查redis中也存了数据。