MrJazsohanisharma

CRUD with Redis using Spring Boot

Blog ads

Basic CRUD with Redis using Spring Boot

In this blog post, we will create a simple Spring Boot application that performs CRUD operations using Redis as the data store. Redis is an in-memory data structure store that can be used as a database, cache, and message broker. Its performance and simplicity make it an excellent choice for many applications.

Prerequisites

  • Java Development Kit (JDK) 11 or later
  • Spring Boot 2.5 or later
  • Maven or Gradle
  • Redis installed and running on your machine

Set Up Your Spring Boot Application

First, we will create a new Spring Boot project. You can use Spring Initializr to bootstrap our application.

  • Choose "Maven Project" or "Gradle Project".
  • Select Java as the language.
  • Choose your preferred Spring Boot version.
  • Add the following dependencies:
    • Spring Web
    • Spring Data Redis
    • Lettuce (Redis client)
    • Spring Boot DevTools (optional)
    • Spring Boot Starter Test (optional for testing)

After configuring the dependencies, click on "Generate" to download the project and extract it to your workspace.

Configure Redis in application.properties

Open the src/main/resources/application.properties file and add the following configurations:

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

Create a Simple Model

Next, we need to create a simple model for our application. Let’s create a Product class:

    
package com.example.demo.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;

@RedisHash("product")
public class Product {
    @Id
    private String id;
    private String name;
    private double price;

    // Constructors, getters, and setters
    public Product() {}

    public Product(String id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}
    

Create the Repository

Next, we need a repository interface to handle database operations. Create a new interface named ProductRepository:

    
package com.example.demo.repository;

import com.example.demo.model.Product;
import org.springframework.data.repository.CrudRepository;

public interface ProductRepository extends CrudRepository<Product, String> {
}
    

Create the Controller

Now, let’s create a controller that will handle RESTful requests for our Product model. Create a new class named ProductController:

    
package com.example.demo.controller;

import com.example.demo.model.Product;
import com.example.demo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        Product savedProduct = productRepository.save(product);
        return new ResponseEntity<>(savedProduct, HttpStatus.CREATED);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable String id) {
        Optional<Product> product = productRepository.findById(id);
        return product.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping
    public Iterable<Product> getAllProducts() {
        return productRepository.findAll();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable String id, @RequestBody Product product) {
        if (!productRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        product.setId(id);
        Product updatedProduct = productRepository.save(product);
        return ResponseEntity.ok(updatedProduct);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable String id) {
        if (!productRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        productRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}
    

Run the Application

Now that everything is set up, you can run your Spring Boot application. If using Maven, simply execute:

    
mvn spring-boot:run
    

Make sure your Redis server is running. You can now test the CRUD operations using tools like Postman or using curl commands.

Testing the CRUD Operations

Here are a few example requests you can use to test your REST API:

Create a Product

    
curl -X POST -H "Content-Type: application/json" -d '{"id": "1", "name": "Product A", "price": 10.0}' http://localhost:8080/api/products
    

Retrieve a Product

    
curl -X GET http://localhost:8080/api/products/1
    

Update a Product

    
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Updated Product A", "price": 12.0}' http://localhost:8080/api/products/1
    

Delete a Product

    
curl -X DELETE http://localhost:8080/api/products/1
    

Conclusion

In this blog post, we demonstrated how to set up a simple Spring Boot application that performs CRUD operations using Redis as a data store. Redis is fast and can handle a lot of read/write operations, making it perfect for use in modern applications. Feel free to extend this application with more complex features such as validation, error handling, or even integrating with a front-end framework!

ads

Previous Post Next Post