Search Tutorials


Spring Boot + Session Management Example Using Redis | JavaInUse

Spring Boot + Session Management Example Using Redis

In a previous tutorial we had implemented Session Management + Spring Boot +JDBC where we used JDBC as the data store for storing Session Information.
In this post we will be implementing Session Management + Spring Boot +Redis where we used Redis as the data store for storing Session Information.
First let us have a look at what is session management and how can it be accomplished.

What is Session Management?

We all know that HTTP is a stateless protocol. All requests and responses are independent. The server cannot distinguish between new visitors and returning visitors. But sometimes we may need to keep track of client's activity across multiple requests. This is achieved using Session Management. It is a mechanism used by the Web container to store session information for a particular user.
Session management can be achieved in one of the following ways-
  • Cookies
  • Hidden form field
  • URL Rewriting
  • HttpSession
In this example we will be making use of HttpSession to achieve Session management. Also we will be using the Spring Session module
Spring Session consists of the following modules:
  • Spring Session Core - provides core Spring Session functionalities and APIs
  • Spring Session Data Redis - provides SessionRepository and ReactiveSessionRepository implementation backed by Redis and configuration support
  • Spring Session JDBC - provides SessionRepository implementation backed by a relational database and configuration support
  • Spring Session Hazelcast - provides SessionRepository implementation backed by Hazelcast and configuration support
In this post we will be using Spring Session Data Redis to store spring session information. By default Apache Tomcat stores HTTP session objects in memory.
Spring Boot HTTP Session
In order to achieve writing the session objects to Redis, we dont have to write any code. Spring Boot provides us this functionality out of the box by specifying the following configuration property
spring.session.store-type=redis
Spring session replaces the HttpSession implementation by a custom implementation. To perform this task spring session creates a SessionRepositoryFilter bean named as springSessionRepositoryFilter.
boot-50_6

Lets Begin-

Getting started with Redis

We will first need to install Redis. For this follow the below steps-
  • Go to Redis Downloads Page at github and download the Redis zip file.
  • Go to the location where the downloaded contents are unzipped
    Install Redis on Windows
    Use the following command to start Redis Server
    redis-server.exe --maxheap 1024M
    

    Start Redis Server on Windows
  • Open a new Command Line Window and again go to the location where the downloaded contents are unzipped and use the following command to start the Redis Client which we will use to monitor Redis.
    redis-cli.exe
    
    Once started use the monitor command as follows-
    monitor
    

    Start Redis Client on Windows

Spring Boot + Session Management + Redis

Maven Project will be as follows-

boot-50_5

In the Maven we need the Spring Session dependency.Maven will be as follows-
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javainuse.spring</groupId>
	<artifactId>Spring-Boot-Session-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>Spring-Boot-Session-Example</name>
	<description>Spring-Boot-Session-Example</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>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 SpringBootHelloWorldApplication.java as below-
package com.javainuse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootSessionApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootSessionApplication.class, args);
	}
}
Create the Controller class as follows-
package com.javainuse.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 SpringSessionController {

	@GetMapping("/")
	public String home(Model model, HttpSession session) {
		@SuppressWarnings("unchecked")
		List<String> messages = (List<String>) session.getAttribute("MY_SESSION_MESSAGES");

		if (messages == null) {
			messages = new ArrayList<>();
		}
		model.addAttribute("sessionMessages", messages);
		model.addAttribute("sessionId", session.getId());

		return "index";
	}

	@PostMapping("/persistMessage")
	public String persistMessage(@RequestParam("msg") String msg, HttpServletRequest request) {
		@SuppressWarnings("unchecked")
		List<String> msgs = (List<String>) request.getSession().getAttribute("MY_SESSION_MESSAGES");
		if (msgs == null) {
			msgs = new ArrayList<>();
			request.getSession().setAttribute("MY_SESSION_MESSAGES", msgs);
		}
		msgs.add(msg);
		request.getSession().setAttribute("MY_SESSION_MESSAGES", msgs);
		return "redirect:/";
	}

	@PostMapping("/destroy")
	public String destroySession(HttpServletRequest request) {
		request.getSession().invalidate();
		return "redirect:/";
	}
}


So if not already present,we create an ArrayList named MY_SESSION_MESSAGES in a HTTPSession and persist messages in this list
Spring Boot HTTP Session Object
The application.properties will be as follows-
spring.session.store-type=redis
spring.redis.host=localhost
spring.redis.port=6379

The index.html we make use of thymleaf for displaying the session messages along with the session id.
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Session Example</title>
</head>
<body>
	<div>
		<form th:action="@{/persistMessage}" method="post">
			<textarea name="msg" cols="40" rows="2"></textarea>
			<br> <input type="submit" value="Save Message" />
		</form>
	</div>
	<div>
		<h2>Messages</h2>
		<ul th:each="message : ">
			<li th:text="">msg</li>
		</ul>
	</div>
	<div>
		<h2>Session ID</h2>
		Current Session ID is <span th:text="" />
	</div>
	<div>
		<form th:action="@{/destroy}" method="post">
			<input type="submit" value="Destroy Session" />
		</form>
	</div>
</body>
</html>
Compile and the run the SpringBootHelloWorldApplication.java as a Java application.
Go to localhost:8080
Spring Boot + Session Management + Redis
We can add the items to be stored in the session. The Spring session will automatically create or update existing session info using Redis.
Redis Session

Download Source Code

Download it -
Spring Boot + Session Management + Redis

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions