Spring Boot Session Management using Redis Example
What is Session Management?
Session management is the process of securely handling multiple requests to a web-based application or service from a single user or entity. HTTP is used to communicate between websites and browsers, and a session is a series of HTTP requests and transactions created by the same user. The session management implementation specifies the process for sharing and continually exchanging the session ID between the user and the web application.
Note : The full source code for Spring boot session management example can be downloaded at the end of this article.
You can also learn how to authenticate user using Spring Boot + JWT Token.
As HTTP protocol is stateless, and to keep track of user interactions, we need session management. Session management is a web container framework used to store session data for a specific user.
You can handle the session in one of the following ways-:
-
A Cookies
is a data sent from a website and saved by the user's web browser on the user's computer as the user browses. -
Hidden form field
is a hidden data, which will not be shown to user and can not be modified. However, when the user submits the form, hidden data would be sent. -
URL Rewriting
is the method of modifying the URL parameters. -
HttpSession
enables data to be associated with individual visitors.
You may enhance your application's performance even further by storing static or frequently requested data in memory/cache provider. Refer Spring Boot Caching Example to learn more.
Managing user session is very important in most of the web applications. Mainly we have been maintaining user session data in cluster environment with load balancer in front of server nodes to distribute the traffic accordingly. So to manage the session environment like in production would be very crucial. In distributed environment, we can manage session in below ways.
-
Sticky Session
In this type of session, load balancer would always route same client request to same node. But here if that node goes down, session would also be gone. -
Session Replication
To overcome sticky session problem, session replication replicates session data to multiple servers. So in case of any node goes down, session data would always be available with other nodes. -
Session Data in a Persistent DataStore
Here in this case session would not stored in server memory, instead, it will be store in database(RDBMS, Redis, HazelCast, MongoDB etc) with unique id called SESSION_ID.
If you want to do certain important tasks whenever an HTTP Session is created or deleted, use the Spring Boot + Session Listener Example.
Let's see how to use spring boot session management with Session Data in a Persistent DataStore. In this case, we will use HTTPSession to manage the session. We'll also use the Spring Session module
The following modules are included in the Spring Session:
-
Spring Session Core
- Spring Session core APIs -
Spring Session Data Redis
- Provides session repository for Redis database session management. -
Spring Session JDBC
- Provides session repository for relational database like MYSQL etc session management. -
Spring Session Hazelcast
- Provides session repository for Hazelcast session management.
By default, Apache Tomcat store HTTP session objects in memory. However we can make use of HTTPSession with Spring Session Data Redis to store the session data in persistent storage (Redis) in Spring Boot application. Let's see how to use Spring Boot Session Management with Session Data in a Persistent DataStore.
Install Redis
Follow the steps given here to install Redis Client/Server to test this application.We don't have to write any code to write the session objects to Redis server, as given below just use below property.
spring.session.store-type=redis
Spring Session Data Redis provides SessionRepository and ReactiveSessionRepository implementation backed
by Redis and configuration support.
Project will look as given below:
Create Spring Boot Rest Application
- Go to Spring on official site https://start.spring.io/
- Select Maven project, add dependencies
- Click on Generate the project Button.
- Import this generated project in Eclipse IDE as existing maven project and follow below steps.
Add Spring Session Redis dependency in pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.techgeeknext</groupId>
<artifactId>SpringBootSessionManagementRedis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootSessionManagement</name>
<description>Demo project for Spring Boot Session Management using Redis</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Create the Main Class
- SpringBootSessionManagementRedispackage com.techgeeknext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootSessionManagementRedis {
public static void main(String[] args) {
SpringApplication.run(SpringBootSessionManagementRedis.class, args);
}
}
Create the Controller
to handle user request, process user's data and store the data in NOTES_SESSION attribute in session.package com.techgeeknext.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class SpringBootSessionController {
@PostMapping("/addNote")
public String addNote(@RequestParam("note") String note, HttpServletRequest request) {
//get the notes from request session
List<String> notes = (List<String>) request.getSession().getAttribute("NOTES_SESSION");
//check if notes is present in session or not
if (notes == null) {
notes = new ArrayList<>();
// if notes object is not present in session, set notes in the request session
request.getSession().setAttribute("NOTES_SESSION", notes);
}
notes.add(note);
request.getSession().setAttribute("NOTES_SESSION", notes);
return "redirect:/home";
}
@GetMapping("/home")
public String home(Model model, HttpSession session) {
List<String> notes = (List<String>) session.getAttribute("NOTES_SESSION");
model.addAttribute("notesSession", notes!=null? notes:new ArrayList<>());
return "home";
}
@PostMapping("/invalidate/session")
public String destroySession(HttpServletRequest request) {
//invalidate the session , this will clear the data from configured database (Mysql/redis/hazelcast)
request.getSession().invalidate();
return "redirect:/home";
}
}
Add below configuration properties in application.properties
spring.session.store-type=redis
## redis server host, replace localhost below with your hostname
spring.redis.host=localhost
## redis port
spring.redis.port=6379
Create home.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Session Management Example</title>
</head>
<body>
<div>
<form th:action="@{/addNote}" method="post">
<textarea name="note" cols="40" rows="2"></textarea>
<br> <input type="submit" value="Add Note" />
</form>
</div>
<div>
<form th:action="@{/invalidate/session}" method="post">
<input type="submit" value="Destroy Session" />
</form>
</div>
<div>
<h2>Notes</h2>
<ul th:each="note : ">
<li th:text="">note</li>
</ul>
</div>
</body>
</html>
Our demo is ready, now first start the Redis client/server, compile and the run the SpringBootSessionManagementRedis.java and go to home page http://localhost:8080/home.
Enter Note in Textarea and click on Add Note Button to add note in session.
Go to home page, Note has been added to the session.
Add second Note in the session.
Now if you go to the Redis and see that Note1 and Note2 created in the NOTE SESSION object.
- NOTE_SESSION- Tested using Redis Desktop Manager
Click on Destroy Session, Spring Boot will delete data (NOTES_SESSION) from redis.
Now go to home page, session data got cleaned.
As you have seen how Spring boot store user session data to database, which will make very easy to maintain session data in cluster environment as well.
Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot Session Management using Redis