Spring Boot Redis CRUD Example

Redis is an in-memory data structure store often used as a database, cache, and message broker. It is known for its high performance and flexibility. Integrating Redis with Spring Boot can enhance your application's performance by leveraging Redis' fast data access capabilities. In this tutorial, we will cover how to set up and use Redis with Spring Boot, focusing on CRUD (Create, Read, Update, Delete) operations using a Student entity.

Prerequisites

  • JDK 17 or later
  • Maven or Gradle
  • Docker (optional, for running Redis locally)
  • Spring Boot (version 3.2+ recommended)
  • IDE (IntelliJ IDEA, Eclipse, etc.)

Step 1: Set Up a Spring Boot Project

Use Spring Initializr to create a new project with the following configuration:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 3.2.x
  • Dependencies: Spring Web, Spring Data Redis

Download and unzip the project, then open it in your IDE.

Example Spring Boot Application

We will create a simple Spring Boot application that interacts with Redis to perform CRUD operations on a Student entity.

1.1 Application Class

package com.example.redis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RedisApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisApplication.class, args);
    }
}

Step 2: Running Redis Locally

Using Docker

If you have Docker installed, you can run Redis using the following command:

docker run --name redis -d -p 6379:6379 redis

Installing Redis Locally

Alternatively, you can install Redis on your local machine by following the installation instructions for your operating system from the Redis website.

Step 3: Configure Redis in Spring Boot

3.1 Add Redis Configuration

Add the following configuration to your src/main/resources/application.properties file:

# src/main/resources/application.properties

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

3.2 Create a Redis Configuration Class

Create a configuration class named RedisConfig in the com.example.redis.config package.

package com.example.redis.config;

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.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

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

Explanation:

  • RedisTemplate<String, Object>: Provides high-level abstractions for Redis interactions.
  • StringRedisSerializer: Serializes keys as strings.
  • GenericJackson2JsonRedisSerializer: Serializes values as JSON using Jackson.

Step 4: Create a Student Entity

Create a model class named Student in the com.example.redis.model package.

package com.example.redis.model;

import java.io.Serializable;

public class Student implements Serializable {

    private String id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    // Getters and setters

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Step 5: Create a Student Repository

Create a repository interface named StudentRepository in the com.example.redis.repository package. This interface will define methods for interacting with Redis.

package com.example.redis.repository;

import com.example.redis.model.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends CrudRepository<Student, String> {
}

Step 6: Create a Student Service

Create a service class named StudentService in the com.example.redis.service package.

package com.example.redis.service;

import com.example.redis.model.Student;
import com.example.redis.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    public Iterable<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    public Optional<Student> getStudentById(String id) {
        return studentRepository.findById(id);
    }

    public Student createStudent(Student student) {
        return studentRepository.save(student);
    }

    public Optional<Student> updateStudent(String id, Student student) {
        return studentRepository.findById(id).map(existingStudent -> {
            existingStudent.setName(student.getName());
            existingStudent.setAge(student.getAge());
            return studentRepository.save(existingStudent);
        });
    }

    public void deleteStudent(String id) {
        studentRepository.deleteById(id);
    }
}

Step 7: Create a REST Controller

Create a controller class named StudentController in the com.example.redis.controller package.

package com.example.redis.controller;

import com.example.redis.model.Student;
import com.example.redis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public Iterable<Student> getAllStudents() {
        return studentService.getAllStudents();
    }

    @GetMapping("/{id}")
    public Optional<Student> getStudentById(@PathVariable String id) {
        return studentService.getStudentById(id);
    }

    @PostMapping
    public Student createStudent(@RequestBody Student student) {
        return studentService.createStudent(student);
    }

    @PutMapping("/{id}")
    public Optional<Student> updateStudent(@PathVariable String id, @RequestBody Student student) {
        return studentService.updateStudent(id, student);
    }

    @DeleteMapping("/{id}")
    public void deleteStudent(@PathVariable String id) {
        studentService.deleteStudent(id);
    }
}

Step 8: Test the Application

8.1 Run the Application

Run the Spring Boot application using your IDE or the command line:

./mvnw spring-boot:run

8.2 Verify CRUD Operations

Use a tool like Postman or curl to test the endpoints.

  1. Create a Student:

    • URL: http://localhost:8080/students
    • Method: POST
    • Body:
      {
        "id": "1",
        "name": "John Doe",
        "age": 20
      }
      
  2. Get All Students:

    • URL: http://localhost:8080/students
    • Method: GET
  3. Get a Student by ID:

    • URL: http://localhost:8080/students/1
    • Method: GET
  4. Update a Student:

    • URL: http://localhost:8080/students/1
    • Method: PUT
    • Body:
      {
        "name": "Jane Doe",
        "age": 21
      }
      
  5. Delete a Student:

    • URL: http://localhost:8080/students/1
    • Method: DELETE

You should see the correct responses and verify that the data is stored, retrieved, updated, and deleted from Redis.

Conclusion

In this tutorial, you have learned how to integrate Redis with Spring Boot to perform CRUD operations using a Student entity. We covered:

  • Setting up a Spring Boot project with Redis dependencies.
  • Running Redis locally using Docker or installing it on your machine.
  • Configuring Redis in Spring Boot.
  • Creating a Student entity, repository, service, and REST controller.
  • Testing the CRUD operations using Postman or curl.

By following these steps, you can leverage Redis to build robust and scalable Spring Boot applications.

Comments