Spring Data – Redis

Spring Data Initial Concept

A brief discussion on the Initial Concept of Spring Data is described in this springcavaj – Spring Data page with an architecture diagram.

This guide will provide an understanding of Spring Data to build an application that stores and retrieves data using Mongo DB as the underlying database.

What is Redis

Redis (REmote DIctionary Server) is an open-source, in-memory, No-SQL key/value store that is used primarily as an application cache or quick-response database. It is very fast in comparison to traditional databases. It provides various data structures to handle the different types of data efficiently.

Redis stores the data in memory rather than on a disk or SSD, due to which it is fast.

Use Case of Redis

  1. Caching – It is commonly used to cache frequently accessed data to reduce the load on the database.
  2. Session Store – It can be used to store session data of web applications for fast access and high availability.
  3. Real-Time Analytics – It can be used for real-time data analytics and monitoring applications.
  4. Message Queue – Redis Pub/Sub and list structures can be used to implement message queues.
  5. Leaderboards and Counting – Redis sorted set data structure is perfect for implementing leaderboards and real-time counting applications.
  6. Geospatial Data – It supports geospatial data, one can query like finding the nearest locations to a given point.
  7. Rate Limiting – It can be used to implement rate limiting for APIs to control the no. of requests a client can make.

Advantages of using Redis

  • High Performance
  • Versatile Data Structure
  • Persistence
  • Replication and High Availability
  • Scalability
  • Simplicity and Ease of use
  • Pub/Sub Messaging
  • Atomic Operations
  • LUA Scripting

Using Spring Data with Spring Boot and using Redis Cache with MongoDB as a database

I have created a Demo project named spring-data-redis-masterclass and uploaded it to my personal GitHub account. One can clone the project and run it locally in their system. But before that, the prerequisite software needs to be installed on the local machine. All the software lists are provided in the README.md file of the above repository. And after that in the same README.md file I have provided the steps to install, clone, and run the application locally.

  • Brief Description – I have developed an application using Java, Maven, Spring Boot, Spring Data, Mongo, and Redis. The main goal of this application is to use Redis as a cache and reduce the load to call the MongoDB database every time to get the data.
  • Software Used – Software required to develop this application.
    • Spring Tool Suite-4.7.0-RELEASE – If the latest version is available then download that one
    • Apache Maven 3.6.3 – If the latest version is available then download that one
    • Java 8 – Not less than Java8
    • Git 2.27.0 – The latest version as available
    • Redis – To install Redis in your Windows machine you need to install Ubuntu, detailed link is provided in the README.md file of the spring-data-redis-masterclass.
    • Redis Insight – The client to access Redis.
    • Mongo 4.2.8 – MongoDB Server
    • Robo 3T 1.3.1 – MongoDB Client to see the data as persisted in DB. You can download any other client as available in the market
    • Postman v8.3.0 – To test the REST Service
  • Project Components – The above application is a Spring Boot, Maven project. In support of accessing Redis, I have used a dependency named spring-boot-starter-data-redis. Other dependencies as spring-boot-starter-data-mongodb to use MongoDB as the underlying database for this application.
<!-- Redis dependency -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--  Spring Mongo Dependency -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

To connect to the Redis instance you need to define certain properties which I have defined in application.properties file.

spring.redis.host=localhost
spring.redis.port=6379
  • Structure of the Project – To use Spring Data with Redis and its libraries in your project you need to structure it in the right way.
  • Redis Configuration – To connect to Redis apart from the above-defined properties you also need to configure the RedisTemplate Bean.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableRedisRepositories
public class SpringDataRedisConfiguration {

    @Bean
    RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		template.setKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		return template;
	}

}

In the above class, we create the configuration to connect with Redis from the backend code. In the above case, we set the key as String and the value as Object, and we have used the configuration of application.properties file to create the RedisConenctionFactory.

Now in your service class, you will use the RedisTemplate<String, Object> bean to get and save the values in Redis.

To save a value from Redis:

redisTemplate.opsForValue().set(EMPLOYEE_KEY_PREFIX + savedEmployee.getEmployeeId(), savedEmployee);

To get a value from Redis:

Employee employee = (Employee) redisTemplate.opsForValue().get(EMPLOYEE_KEY_PREFIX + employeeId);
  • Testing the application – There is no UI component for this application so I have used Postman to test the REST API Endpoints. But you can integrate the UI segment and can do proper POC on your own.
  1. You clone the application from GitHub and set up the application locally in any one of the IDEs like Spring Tool Suite (STS) or Eclipse.
  2. Right-click on the application
  3. Click the Option Run As
  4. Select the option Spring Boot App.
  5. It will start the application in port no 7123

GitHub Code Link

Download the Source Code from GitHub

Common Faced Problems

Spring Data Problems

Interview FAQs

Spring Data Interview FAQs

Other Useful Links of Spring Data

Spring Data using RDBMS (MySQL DB) and Spring REST

Spring Data using NoSQL DB and Spring REST

Spring Data using Cypher Neo4j DB and Spring REST

Other Useful Links

Spring REST

Spring RabbitMQ

Spring Apache Kafka – Producer & Consumer

Spring Kafka Confluent – Set Up

Spring Kafka Confluent – Producer & Consumer

Spring Apache Kafka Connect

Spring Mongo Kafka Connector

Spring Cloud using Google Cloud SQL & Google Cloud Storage

Spring Cloud using Google Cloud Pub-Sub

Spring Cloud using Google Cloud Spanner

Spring Reactive Web Flux Programming