Open In App

Spring Boot – CRUD Operations Using Redis Database

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.



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:

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:

Spring initializr dashboard with the list of dependencies required for our project

Note: After project Bootstrap change Spring Boot version i.e. 2.4.5

1.1: Dependency for Redis




<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.

spring.redis.host=localhost
spring.redis.port=6379

Step 2. Implementing CRUD APIs

We will be following the Spring MVC code structure:

Step 2.1: Entity

Data Entity layer for Customer.java, we will be storing only following customer data only:




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;
}

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.




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.
    
}

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:

  1. addCustomer – to insert new customer data into the Redis database.
  2. getListOfCustomers – to fetch All the customers from the Redis database.
  3. getCustomer – to fetch Customer data using ID from Redis Database.
  4. updateCustomer – to update an existing customer in the Redis database using ID.
  5. delete customer – to delete an existing customer from the Redis database using ID.




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:

  1. addCustomer: will be used to insert new customer data into the Redis database.
  2. getAllCustomers: this method will run a fetch query in the Redis Database to get a list of all the customers.
  3. getCustomerById: this method will perform a fetch operation using an ID from the Redis repository.
  4. updateCustomerById: method will update the existing customer with the latest customer data.
  5. deleteCustomerById: it will delete the existing customer from the Redis repository.




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

Testing – Fetch list of all customer API using Postman

List of all Customers inside Redis Database

List of all Customers inside Redis Database

3.2: Add new Customer API

Testing – add new customer API using Postman

Database view of Customer Data into Redis Database.

3.3: Update Existing Customer API

Testing – update existing customer data API using Postman

3.4: Delete Existing Customer API

Testing – delete existing customer API using Postman

Redis Database Commands

To verify the customer data into the Redis Database. You need to know a few commands, which are listed below.

Conclusion

In the article, we have covered how you can use Redis as a Database for your Spring Boot Application, in the following steps.


Article Tags :