最新nginx负载均衡集群tomcat1和tomcat2,session共享解决方案-springsession详细教程

前言

1.如果让你做为企业的系统开发lead,随着系统流量的增加,现在企业要求使用集群来解决减轻服务器压力的方案,你会考虑到哪些问题?
我们是不是首先会考虑的会话共享的问题,比如我通过nginx集成tomcat做负载均衡,比如现在用户访问登录请求,nginx通过反向代理访问tomcat1后登录成功,在tomcat1中保存了session信息,那么用户进行系统操作时,这时可能nginx通过反向代理把请求转发到了tomcat2中,这时tomcat2中没有登录信息,会提示用户需要重新登录,这时可想而知,用户是不是就烦恼了,我刚登录了,怎么又让我登录,体验非常不好,这就是我们需要首先解决的session共享的问题。
2.session共享的几种解决方案

  • 第一种方案是通过web容器扩展插件来解决,比如tomcat的tomcat-redis-session-manager插件,这种方式有点事对于项目是透明的,无需修改代码就可以实现,但是依赖于web容器,如果容器升级或者更换,还需要重新配置;
  • 第二种是使用Nginx负载均衡的ip_hash策略实现用户每次访问都绑定到同一台具体的后台tomcat服务器实现session总是存在;
  • 第三种是自己写一套Session会话管理的工具类,在需要使用会话的时候都从自己的工具类中获取,而工具类后端存储可以放到Redis中,这个方案灵活性很好,但开发需要一些额外的时间。

第四种是使用Spring session框架;Spring Session提供了一个API和用于管理用户会话信息的实现。无需修改代码,只需在项目中配置即可,不依赖于web容器,方便升级和维护,可集成redis中;

一、软件架构

  1. nginx-1.19.0 windows 64位版本
  2. apache-tomcat-9.0.30-windows-x64
  3. Redis-x64-3.2.100
  4. Apache Maven 3.5.3
  5. java web项目集成Spring Session

二、java项目配置

  1. 新建一个java maven web项目,项目名根据自己的爱好起名,我这里起的是springsession;
  2. web.xml配置如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         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">

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:application-session.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>


  <!--DelegatingFilterProxy将查找一个Bean的名字springSessionRepositoryFilter丢给一个过滤器。为每个请求
  调用DelegatingFilterProxy, springSessionRepositoryFilter将被调用-->
  <filter>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>


  <filter-mapping>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ERROR</dispatcher>
  </filter-mapping>


  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>
        
  1. index.jsp源码如下,项目部署到tomcat1时下面输出内容改为tomcat1,部署到tomcat2时,输出内容改为tomcat2
<html>
<body>
<h2>Hello World! tomcat2</h2>
</body>
</html>

  1. 新建一个LoginServlet,用来模拟假设登陆的操作,并不需要实际的输入用户名、密码,源码如下:
package com.springsession.demo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	 @Override
	    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
	        HttpServletRequest request = (HttpServletRequest) req;
	        HttpServletResponse response = (HttpServletResponse) res;
	        request.getSession().setMaxInactiveInterval(10*1000);
	        response.sendRedirect(request.getContextPath() + "/session");

	    }
}

5.再新建一个SessionServlet用来输出sessionid,这里的输出tomcat1和tomcat2根据部署到的tomcat进行对应修改,源码如下:

package com.springsession.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/session")
public class SessionServlet extends HttpServlet {
	 @Override
	    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

	        HttpServletRequest request = (HttpServletRequest) req;
	        HttpServletResponse response = (HttpServletResponse) res;
	        System.out.println(request.getRemoteAddr());
	        System.out.print(request.getRemoteHost() + " : " + request.getRemotePort());
	        String sesssionID = request.getSession().getId();
	        PrintWriter out = null;
	        try {
	            out = response.getWriter();
	            out.append("tomcat2 ---- sesssionID : " + sesssionID);
	        }catch (Exception e){
	            e.printStackTrace();
	        }finally {
	            if(out != null){
	                out.close();
	            }
	        }

	    }
}

6.pom配置源码如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.session.jr</groupId>
  <artifactId>spring-session</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring-session Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>
      <jdk.version>1.8</jdk.version>
      <spring.version>4.3.4.RELEASE</spring.version>
      <spring-session.version>1.3.1.RELEASE</spring-session.version>
    </properties>

    <dependencies>
    	    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api  -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>${spring-session.version}</version>
            <type>pom</type>
        </dependency>
        
       <dependency>
            <groupId>biz.paluch.redis</groupId>
            <artifactId>lettuce</artifactId>
            <version>3.5.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>


    </dependencies>
  
  
  <build>
    <finalName>spring-session</finalName>
  </build>
</project>

7.在resources目录下新建application-session.xml文件,配置源码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:annotation-config/>


    <!--创建一个Spring Bean的名称springSessionRepositoryFilter实现过滤器。
    筛选器负责将HttpSession实现替换为Spring会话支持。在这个实例中,Spring会话得到了Redis的支持。-->
    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
    <!--创建了一个RedisConnectionFactory,它将Spring会话连接到Redis服务器。我们配置连接到默认端口(6379)上的本地主机!-->
    <bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"/>

</beans>

三、修改tomcat1和tomcat2的配置

在这里插入图片描述
在这里插入图片描述

四、配置nginx

在这里插入图片描述

五、打包发布测试

注意:java项目里的SessionServlet输出根据部署的tomcat机器号,进行修改打包部署;

out.append("tomcat2 ---- sesssionID : " + sesssionID);
  1. 启动nginx
  2. 启动redis
  3. 分别在tomcat1和tomcat2中部署springsession项目,并启动
  4. 访问http://localhost/springsession/login会重定向到http://localhost/springsession/session连接打印出来sessionid和tomcat服务器号,如下图;
    在这里插入图片描述
    5.刷新浏览器会访问到tomcat2,我们可以看到也是同样的sesssion,这样通过springsession集成redis完成session共享的解决方案;
    在这里插入图片描述
    6.通过查看redis也可以看到sessionid已经同步到了redis中,如下图:
    在这里插入图片描述

-END-

如果你喜欢我的分享,想结交更多的JAVA朋友,或者交流技术问题,欢迎关注微信公众号
发送“springsession”获取源码包
java学长
学习更多java技术干货,提升职场技术水平!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT悍将阿瑞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值