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.
- 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 )
Note: 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.w3wiki.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.w3wiki.RedisCRUD.repository; import org.w3wiki.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.w3wiki.RedisCRUD.controller; import java.util.ArrayList; import java.util.List; import org.w3wiki.RedisCRUD.entity.Customer; import org.w3wiki.RedisCRUD.repository.CustomerRepo; import org.w3wiki.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.w3wiki.RedisCRUD.service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import lombok.RequiredArgsConstructor; import org.w3wiki.RedisCRUD.entity.Customer; import org.w3wiki.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
List 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.
3.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.
Database 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.
3.4: Delete Existing Customer API
- Select the DELETE method.
- Use URL β http://localhost:8080/customer/{id}, where the customer is deleted based on ID.
Redis 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.