Session definition:

* Refer to the koA-session source code

  • Session is a concept, a data object that stores information about visitors.
  • Session storage is defined by the developer and can be stored in memory, Redis, mysql or even cookies.
  • When a user visits for the first time, we create a session for the user and insert his “key key” into the cookie. So even though the HTTP request is stateless, we can retrieve the visitor’s “key key” through cookies, and then retrieve the corresponding visitor’s session from the session collection of all visitors.
  • The server session does not immediately expire when the browser is closed. The session middleware implements a set of management methods by itself. When the access interval exceeds maxAge, the session will expire.

Session implementation principle:

  • 1. Create a Session object on the server when sending a request to the server for the first time. This object has a unique ID

  • 2. A special Cookie object is created when the Session object is created. The name of the Cookie object is a fixed value JSESSIONID, and the value of the Cookie object is the ID of the Session object.

  • 3. In the future, the browser will carry this special Cookie object when sending

  • 4. After the server obtains the value of the Cookie object of the JESSIONID, it searches for the Session object corresponding to it in the server to distinguish different users

Session = request.getSession()

This can be proved with the following code:

package xdp.gacl.session;

import java.io.IOException; 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 SessionDemo1 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF=8"); response.setContentType("text/html; charset=UTF-8"); Session = request.getSession(); // Use the request object getSession() to get a session. Session. setAttribute("data", "it's a Muggle "); String sessionId = session.getid (); If (session.isnew ()) {response.getwriter ().print("session created successfully, session ID: "+sessionId); }else {response.getwriter ().print(" the session id is: +sessionId); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }Copy the code

}

The basic methods of persistent session storage:

Server:

  • A robust Web server provides a mechanism for Session persistence, which stores Session objects in memory to a persistent storage device (such as a hard disk) when needed (such as when the server is down)Object serializationWhen the Session object needs to be reloaded (such as when the server is restarted), theObject deserializationReconstructs the Session object in memory.
  • TomcatHTTP sessions are created and maintained through Session Manager, and the StandardManager class is used by default when you have no other Session Manager implementation configured. StandardManager serializes all active HttpSession objects in memory to hard disk files when the Tomcat server is normally shut down, restarted, or the Web application is stopped; When the Web application restarts, serialize the HttpSession object, rebuild the HttpSession object in memory, and all the objects held in the HttpSession (assuming the HttpSession object has not expired).
  • Besides StanardManager, Tomcat also provides our SessionManager persistence implementation class org. Apache. Catalina. Session. PersistentManager, the need to pass through the element configuration to work, Used as a child of the element. Using the PersistentManager, HttpSession objects can be stored in files or database tables. By saving the HttpSession object to a database table, you can maintain the same session in a clustered environment. Two ways to implement sessions in KOA2 (based on Redis and MySQL)
  • 1. Implementation method based on MySQL

This approach requires installing both koA-session-minimal and koA-mysql-session dependencies. perform

NPM install koa-session-minimal koa-mysql-session –save

const session = require(‘koa-session-minimal’);

const MysqlStore = require(‘koa-mysql-session’);

const config = require(‘./config/default.js’); // Database configuration

const Koa = require(‘koa’);

const app = new Koa();

/ / the session storage configuration const sessionMysqlConfig = {user: config. Database. The USERNAME and password: config.database.PASSWORD, database: config.database.DATABASE, host: config.database.HOST, };

Use (session({key: ‘USER_SID’, store: new MysqlStore(sessionMysqlConfig)}));

This will automatically create a table in the database and it will generate a cookie in the browser’s cookie with USER_SID as the key. You can update and delete the session value by using the SESSION attribute of CTX. The disadvantage is that each session operation needs to query the database, which is time-consuming.

  • 2. Implementation method based on Redis

Koa-session2 and Ioredis were used. perform

NPM install KOa-session2 ioredis –save Refer to the project practices and Tests section below for implementation code

Each login can store session information through Redis, because Redis runs directly in memory, so the speed is relatively fast. You can view the session information by using the GET key.

Redis:

Redis is an open source, high-performance key-value store. It is often referred to as a Data Structure Server.

Setting up Sentinel environment under Redis cluster ~ Windows and its practical significance to master-slave mode:

  • Click here for references

To store sessions using iOREdis, refer to the iOREdis interface documentation to provide storage for the Sentinel environment redis

Project practice and test:

In the management system project to achieve the storage of session redis, redis is the sentinel mode cluster

  • After installing the relevant plug-in libraries, first define the Sentinel port for the Redis service to be used

Sentinels: [{host: ‘127.0.0.1’, port: 26379},

{host: '127.0.0.1', port: 26380}, {host: '127.0.0.1', port: 26381}],Copy the code
  • Add them in order in index.js:

const Store = require(‘./app/redis/redis-store’);

app.use(session({

store:new Store(config.redis),

maxAge: 86400000 }))

// Redis handles session persistence

app.use(require(‘./app/interceptors/redis-session’))

  • /app/interceptors/redis-session.js; /app/interceptors/redis-session.js

‘use strict’; const config = require(‘config’);

module.exports=async (ctx,next)=>{

ctx.destroySession=function () {

   var self = this;
   // console.log("destroySession")
   if(self.session){
       self.session=undefined;
       // console.log("shanchu")
       return true;
  }else{
       return false;
   }
Copy the code

}; await next();

}

  • Cancel the destroySession() method of the login reference definition

async function (ctx, next) { const self = this; try {

If (ctx.haslogin ()) {ctx.destroysession (); if (ctx.haslogin ()) {ctx.destroysession (); // Delete session resp.success({data: true}, CTX); } } catch (e) { resp.failed({ desc: e.toString() }, ctx); } finally {// Execute the process to the next middle-ware await next(); }Copy the code

}

Before running the project, build the environment according to the sentinel environment setup guide above, and run the project after installing the relevant libraries in the project