Analysis of the solution to Nginx Session sharing problem

Analysis of the solution to Nginx Session sharing problem

This article mainly introduces the solution to the Nginx Session sharing problem. The example code in the article is very detailed and has a certain reference value for everyone's study or work. Friends in need can refer to it.

Nginx solves the Session sharing problem:

1. Load balancing with nginx or haproxy. For load balancing with nginx, you can add the ip_hash configuration; for load balancing with haproxy, you can use the balance source configuration, so that requests using one IP are sent to the same server;

2. Use the database to synchronize sessions;

3. Use cookies to synchronize session data, but the security is poor, and http requests need to carry parameters, which increases bandwidth consumption;

4.Tomcat configures session sharing;

5. Use session cluster to store Redis;

1: Create a project and start two Tomcats

2: Write a servlet test

package com.zn.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/nginxSessionServlet")
public class SessionIPServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Current request port: "+request.getLocalPort());
    String action = request.getParameter("action");
    //Store a data in Session if(action.equals("setSession")){
      request.getSession().setAttribute("username","zhangsan");
    }else if(action.equals("getSession")){
      response.getWriter().write((String)request.getSession().getAttribute("username"));
    }
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
  }
}

3. Access effect display without Nginx

Access 8080 and 8081 respectively

4. Configure nginx.conf file

upstream myserver{
     ip_hash;
     server 127.0.0.1:8080;
     server 127.0.0.1:8081;
  }
  server{
    listen 81;
    server_name www.bproject.com;
    location / {
      root html;
      proxy_pass http://myserver;
      index index.html index.htm;
    }
  }

5. Visit again

Method 2: Use spring-session+Redis to implement session sharing

1: Import dependencies

<!--Spring boot and redis application basic environment configuration-->
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-redis -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-redis</artifactId>
    </dependency>

    <!--Spring session and redis application basic environment configuration, you need to enable redis before you can use it, otherwise you will get an error when starting Spring boot-->
    <dependency>
      <groupId>org.springframework.session</groupId>
      <artifactId>spring-session-data-redis</artifactId>
    </dependency>

2: Create a controller test

@RestController
public class SessionController {

  @RequestMapping("/setSession")
  public String setSession(HttpServletResponse response, HttpServletRequest request) throws IOException {
    request.getSession().setAttribute("username","wang");
    return "success";
  }

  @RequestMapping("/getSession")
  public String getSession(HttpServletRequest request,HttpServletResponse response){
    String username = (String) request.getSession().getAttribute("username");
    return username;
  }
}

3: application.properties file

server.port=8082
#server.port=8083

#redis configuration spring.redis.password: wang2003

4: Start project testing

Conclusion: This solution is easy to configure, data is secure and stable, efficient, and widely used;

Note: After deleting this data packet in Redis, the session cannot be obtained on ports 8082 and 8083, which means that the session does not exist in the JVM but is transferred to Redis.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed explanation of two ways to implement session persistence in Nginx reverse proxy
  • Implementation of Session Management with Nginx+Tomcat
  • nginx+redis realizes session sharing
  • nginx+tomcat implements load balancing and uses redis session sharing
  • Example of shared session configuration method in Nginx
  • Nginx load balancing multi-site shared session
  • Implementation of nginx worker process loop
  • Detailed explanation of the underlying implementation method of Nginx polling algorithm
  • Nginx dynamically forwards to upstream according to the path in the URL
  • Implementation steps of nginx to build a python-based web environment

<<:  Vue-cli framework implements timer application

>>:  Implementation of MySQL multi-version concurrency control MVCC

Recommend

vue-cli introduction and installation

Table of contents 1. Introduction 2. Introduction...

Analysis of the HTML writing style and reasons of experienced people

1. Navigation: Unordered List vs. Other Label Ele...

How to create a view in MySQL

Basic syntax You can create a view using the CREA...

linux exa command (better file display experience than ls)

Install Follow the README to install The document...

Example of configuring multiple SSL certificates for a single Nginx IP address

By default, Nginx supports only one SSL certifica...

Solution to MySQL service 1067 error: modify the mysql executable file path

Today I encountered the MySQL service 1067 error ...

Vue mobile terminal realizes finger sliding effect

This article example shares the specific code for...

Implementation of react routing guard (routing interception)

React is different from Vue. It implements route ...

MySQL incremental backup and breakpoint recovery script example

Introduction Incremental backup means that after ...

jQuery uses the canvas tag to draw the verification code

The <canvas> element is designed for client...

Make a nice flip login and registration interface based on html+css

Make a nice flip login and registration interface...

Record the steps of using mqtt server to realize instant communication in vue

MQTT Protocol MQTT (Message Queuing Telemetry Tra...

Detailed View of Hidden Columns in MySQL

Table of contents 1. Primary key exists 2. No pri...

Issues with locking in MySQL

Lock classification: From the granularity of data...