Latest nginx load balancing cluster tomcat1 and tomcat2, session sharing solution spring session detailed tutorial

1, Software architecture

  1. nginx-1.19.0 windows 64 bit version
  2. apache-tomcat-9.0.30-windows-x64
  3. Redis-x64-3.2.100
  4. Apache Maven 3.5.3
  5. java web project integration Spring Session

2, java project configuration

  1. Create a new java maven web project. The name of the project is based on your hobbies. I'm starting spring session here;
  2. web.xml The configuration is as follows
<?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 Will find a Bean 's name springSessionRepositoryFilter Throw it to a filter. For each request
  //Call DelegatingFilterProxy, springSessionRepositoryFilter Will be called-->
  <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 The source code is as follows: when the project is deployed to tomcat1, the output is changed to tomcat1; when the project is deployed to tomcat2, the output is changed to tomcat2
<html>
<body>
<h2>Hello World! tomcat2</h2>
</body>
</html>

  1. Create a new LoginServlet to simulate the hypothetical login operation. It does not need to enter the actual user name and password. The source code is as follows:
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. Create a new SessionServlet to output the sessionid. The output tomcat1 and tomcat2 are modified according to the deployed Tomcat. The source code is as follows:

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. The source code of POM configuration is as follows:

<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. Create a new application in the resources directory- session.xml The configuration source code is as follows:

<?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/>


    <! -- create a Spring Bean named springSessionRepositoryFilter to implement the filter.
    The filter is responsible for replacing the HttpSession implementation with Spring session support. In this instance, Spring session is supported by Redis. >
    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
    <! -- a RedisConnectionFactory is created to connect the Spring session to the Redis server. We configure the local host to connect to the defau lt port (6379)! >
    <bean class="org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory"/>

</beans>

3, Modify the configuration of tomcat1 and tomcat2


4, Configure nginx

5, Package release test

Note: the output of SessionServlet in java project is modified, packaged and deployed according to the deployed tomcat machine number;

out.append("tomcat2 ---- sesssionID : " + sesssionID);
  1. start nginx
  2. Start redis
  3. Deploy the spring session project in tomcat1 and tomcat2 respectively, and start
  4. visit http://localhost/springsession/login Will be redirected to http://localhost/springsession/session Connect and print out the sessionid and tomcat server number, as shown below;

    5. Refresh the browser and visit tomcat2. We can see the same session. In this way, we can complete the session sharing solution through spring session integration redis;

    6. By viewing redis, you can also see that the sessionid has been synchronized to redis, as shown in the following figure:
-END-

If you love my sharing, want to make more JAVA friends, or exchange technical problems, welcome to WeChat official account.
Send "spring session" to get the source package
java senior
Learn more java technology dry goods, improve the technical level of the workplace!

Tags: Session Spring Java Redis

Posted on Fri, 19 Jun 2020 03:43:14 -0400 by damic