Spring Boot - CRUD Operations Using Redis Database
Last Updated :
26 Nov, 2023
Redis is an in-memory data structure that is used for faster access to data. It is used to store data that needs to be accessed frequently and fast. It is not used for storing large amounts of data. If you want to store and retrieve large amounts of data you need to use a traditional database such as MongoDB or MYSQL. Redis provides a variety of data structures such as sets, strings, hashes, and lists. For more detail refer to this article Introduction to Redis.
This article will look into how to perform CRUD in Spring Boot using Redis as a Database. Alternatively, Redis has many use cases some are listed.
- Database
- Cache
- Message Broker
Spring Data Redis(SDR) framework and Crud Repository make it easier to interact with the store without writing a bunch of codes. Before starting with any further make sure you have Redis installed on your device.
Note: Command to install Redis is "brew update && brew install redis"
To verify the Redis Installation open Redis-Cli in the terminal and then send a "ping", you must receive a "PONG" as a response.
gfg0341@GFG0341-cs_mshr:~$ redis-cli
127.0.0.1:6379> ping
PONG
Step By Step Implementation
Step 1. Configuration for Redis
In this project, we will be using the following version:
- Spring Boot - 2.4.5
- Redis - 3.2.100
- Java - 17
Make sure to use the same Spring Boot version, as configurations may change for other versions of Spring Boot. You can either do project bootstrap directly through your IDE, or you can select the below method:
- Go to spring initializr website
- Select Project - Maven
- Language - Java
- Spring Boot Version - 2.4.5 (You can do this later by making changes in pom.xml)
- Packaging - Jar
- Java - 17
- Dependencies
- Spring Web
- Lombok
- Spring Data Redis ( Access+driver )
Spring initializr dashboard with the list of dependencies required for our projectNote: After project Bootstrap change Spring Boot version i.e. 2.4.5
1.1: Dependency for Redis
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Note: You can specific the version as <version>3.3.0</version> or any latest.
1.2: Application Properties
It would be best if you do configuration for the following into the application.properties of Spring Boot Application.
- Host: The default host the for application is "localhost"
- Port: By default, the Port for Redis is 6379
spring.redis.host=localhost
spring.redis.port=6379
Step 2. Implementing CRUD APIs
We will be following the Spring MVC code structure:
- Entity Layer (Customer) - Will contain all the required data fields for our Customer.
- Repository Layer (CustomerRepo) - this will provide a bridge between the code and the Redis Store.
- Service Layer (CustomerService) - in this l,ayer we will implement all the required business logic associated with APIs.
- Controller Layer (CustomerController) - this layer will contain all definitions of APIs.
Step 2.1: Entity
Data Entity layer for Customer.java, we will be storing only following customer data only:
- Name - String
- Phone - Long
- Email - String
Java
package org.geeksforgeeks.RedisCRUD.entity;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash(value = "Customer")
public class Customer {
@Id
@Indexed
private int id; // "indexed" for faster retrieval,
// @Id for marking this field as the key
private String name;
private long phone;
private String email;
}
- @Data: It is the part of the Lombok library used to reduce boilerplate code for @Getter, @Setter, etc.
- @AllArgsCostructor: It creates a constructor with all the Data Members as its parameter, part of Lombok.
- @NoArgsCostructor: It creates a constructor with no parameter, part of Lombok.
- @RedisHash(value = "Customer"): It is Spring Data Redis annotation, used to denote a class as Redis Hash. Value = "Customer" means Redis Hash name.
- @Id: It denotes a field as the primary identifier for Redis Hash. i.e. field marked as @id will be used as Key in Redis Hash storage.
- @Indexed: For faster retrieval, we use this annotation, Redis will make an index out of it to optimize the queries.
Notes:
- As per your choice you can extend the number of data members.
- There is no in-built auto-increment feature provided by Redis, like we have in RDMS
Step 2.2: Repository
Next, you can create a Repository interface to make a communication of Spring Boot Application to your Redis Database as CustomerRepo.java in this interface we will extend CrudRepository<Customer, String> which already contains all the methods to perform operations on the database i.e. save, saveAll, delete, findById, findAll, etc. For each entity, you need to create one separate Repository interface to save its data into the Redis Database.
Java
package org.geeksforgeeks.RedisCRUD.repository;
import org.geeksforgeeks.RedisCRUD.entity.Customer;
import org.springframework.data.repository.CrudRepository;
@Repository
public interface CustomerRepo extends CrudRepository<Customer,String> {
// this interface will provide all basic operations for Customer Entity
// To create a custom query you can define a method for that.
}
- @Repository - this annotation will mark the interface as Spring Data Repository
Step 2.3: Controller
Now we need to create a Controller layer to define all the endpoints. We will be declaring all the CRUD APIs, whose method names and descriptions are listed:
- addCustomer - to insert new customer data into the Redis database.
- getListOfCustomers - to fetch All the customers from the Redis database.
- getCustomer - to fetch Customer data using ID from Redis Database.
- updateCustomer - to update an existing customer in the Redis database using ID.
- delete customer - to delete an existing customer from the Redis database using ID.
Java
package org.geeksforgeeks.RedisCRUD.controller;
import java.util.ArrayList;
import java.util.List;
import org.geeksforgeeks.RedisCRUD.entity.Customer;
import org.geeksforgeeks.RedisCRUD.repository.CustomerRepo;
import org.geeksforgeeks.RedisCRUD.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/customer")
public class CustomerController {
// Inject the CustomerService dependency into class
@Autowired
private CustomerService service;
// to insert new customer data into the Redis database.
@PostMapping
public Customer addCustomer(@RequestBody Customer customer){
return service.addCustomer(customer);
}
// to fetch All the customers from the Redis database
@GetMapping
public List<Customer> getListOfCustomers(){
return service.getAllCustomers();
}
// to fetch Customer data using ID from Redis Database
@GetMapping("/{id}")
public Customer getCustomer(@PathVariable int id){
return service.getCustomerById(id);
}
// to update an existing customer in the Redis database using ID.
@PutMapping("/{id}")
public Customer
updateCustomer(@PathVariable int id,
@RequestBody Customer newCustomer){
return service.updateCustomerById(id, newCustomer);
}
// to delete an existing customer from the Redis database using ID
@DeleteMapping("/{id}")
public String deleteCustomer(@PathVariable int id){
service.deleteCustomerById(id);
return "Customer Deleted Successfully";
}
}
Note: As per the requirement you can define more API endpoints.
Step 2.4: Service
Here we will implement all the methods described and used in the controller layer to complete the API operation with the Redis database using your Spring Boot Application. Listed below are the required methods:
- addCustomer: will be used to insert new customer data into the Redis database.
- getAllCustomers: this method will run a fetch query in the Redis Database to get a list of all the customers.
- getCustomerById: this method will perform a fetch operation using an ID from the Redis repository.
- updateCustomerById: method will update the existing customer with the latest customer data.
- deleteCustomerById: it will delete the existing customer from the Redis repository.
Java
package org.geeksforgeeks.RedisCRUD.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.geeksforgeeks.RedisCRUD.entity.Customer;
import org.geeksforgeeks.RedisCRUD.repository.CustomerRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CustomerService {
// Injecting Repository into service class
@Autowired
private CustomerRepo repo;
// to insert new customer data into the Redis database
public Customer addCustomer(Customer customer){
return repo.save(customer);
}
// run a fetch query in the Redis Database
// to get a list of all the customers
public List<Customer> getAllCustomers(){
List<Customer> allCustomer = new ArrayList<>();
repo.findAll().forEach(allCustomer::add);
return allCustomer;
}
// fetch operation to get customer using an ID
public Customer getCustomerById(int id){
Optional<Customer> optionalCustomer
= repo.findById(String.valueOf(id));
return optionalCustomer.orElse(null);
}
// update operation to existing customer using an ID
public Customer updateCustomerById(int id,
Customer newCustomer){
Optional<Customer> existingCustomer
= repo.findById(String.valueOf(id));
if (existingCustomer.isPresent()) {
Customer updatedCustomer
= existingCustomer.get();
updatedCustomer.setName(newCustomer.getName());
updatedCustomer.setPhone(newCustomer.getPhone());
updatedCustomer.setEmail(newCustomer.getEmail());
repo.deleteById(String.valueOf(id));
return repo.save(updatedCustomer);
}
return null;
}
// delete the existing customer
public void deleteCustomerById(int id){
repo.deleteById(String.valueOf(id));
}
}
Step 3. Testing API using Postman
Ensure that your Spring Boot Application is Up and Running and you have Postman installed on your device. Now to test the APIs you need to follow the below step.
3.1: List of all Customer API
- Select the GET method.
- Use URL - http://localhost:8080/customer
Testing - Fetch list of all customer API using PostmanList of all Customers inside Redis Database
- redis-cli - To open the Redis interface
- KEYS Customer:* - To get all KEYS associated with Customer
- HGETALL Customer:101 - Get Customer Data associated with id-101.
List of all Customers inside Redis Database3.2: Add new Customer API
- Select the POST method.
- Use URL - http://localhost:8080/customer
- To insert new customer data, select Body>raw>JSON then customer data in JSON.
Testing - add new customer API using PostmanDatabase view of Customer Data into Redis Database.
- redis-cli - To open the Redis interface
- KEYS Customer:* - To get all KEYS associated with Customer
- HGETALL Customer:101 - Get Customer Data associated with id-101.

3.3: Update Existing Customer API
- Select the PUT method
- Use URL - http://localhost:8080/customer/{id}, where the customer is updated based on ID.
- To update customer data, select Body>raw>JSON then customer data in JSON.
Testing - update existing customer data API using Postman3.4: Delete Existing Customer API
- Select the DELETE method.
- Use URL - http://localhost:8080/customer/{id}, where the customer is deleted based on ID.
Testing - delete existing customer API using PostmanRedis Database Commands
To verify the customer data into the Redis Database. You need to know a few commands, which are listed below.
- redis-cli - To open the Redis interface
- KEYS Customer:* - To get all KEYS associated with Customer
- HGETALL Customer:101 - Get Customer Data associated with id-101
- FLUSHALL - to clear all the data
Conclusion
In the article, we have covered how you can use Redis as a Database for your Spring Boot Application, in the following steps.
- Configuration of Redis as a Database into the project.
- Implementation of all the essential layers, including the entity, controller, etc.
- Testing for each API using Postman.
Similar Reads
Spring Boot - CRUD Operations using MongoDB
CRUD stands for Create, Read/Retrieve, Update, and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a develo
5 min read
Spring Boot - How to Access Database using Spring Data JPA
Spring Data JPA is a robust framework that simplifies the implementation of JPA (Java Persistence API) repositories, making it easy to add a data access layer to the applications. CRUD (Create, Retrieve, Update, Delete) operations are the fundamental actions we can perform on a database. In this art
5 min read
Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as autom
10 min read
Spring Boot - REST API Documentation using OpenAPI
For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of th
4 min read
PostgreSQL CRUD Operations using Java
CRUD (Create, Read, Update, Delete) operations are the basic fundamentals and backbone of any SQL database system. CRUD is frequently used in database and database design cases. It simplifies security control by meeting a variety of access criteria. The CRUD acronym identifies all of the major funct
8 min read
Spring Boot - Spring Data JPA
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any java object directly into a database table. Usually, the name of the object being persisted become
6 min read
How to Create a REST API using Java Spring Boot?
Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
Spring Boot - Caching with Redis
Caching is a crucial optimization technique used to enhance the performance and scalability of web applications. It temporarily stores data in cache memory to reduce access time and load on backend systems. Redis (Remote Dictionary Server) is a popular open-source, in-memory data structure store use
7 min read
Show SQL from Spring Data JPA/Hibernate in Spring Boot
In Spring Boot, Spring Data JPA is part of the larger Spring Data Project that can simplify the development of the data access layers in the spring applications using the Java Persistence API and it can provide a higher-level abstraction over the JPA API. It can reduce the boilerplate code and make
6 min read
How to Work with Databases using Spring Boot?
First, let's start by understanding what Spring Boot is. Spring Boot is a framework that simplifies the process of building and deploying applications by providing a set of pre-configured tools and dependencies. It is built on top of the Spring framework and provides a lightweight and opinionated ap
10 min read