Redis is a key-value store that can be used for multiple purposes. Redis can be used as a database, message broker and a cache.

Spring provides built-in support for data operations, by providing Repository interfaces, that can be used for different data-related operations.

In this article, we will learn how to perform CRUD operation with Spring boot and Redis.

We will create REST APIs to perform CRUD operation with the help of spring data redis starter.

Technologies used are:

  • Spring Boot version: 2.3.1.RELEASE
  • Redis version: 3.2.100
  • Java version 1.8

Installing Redis

If we are using the Windows system, we can download the slightly outdated Redis server in the zip for from here.

Unzip the downloaded zip file and start the server by running the redis-server.exe file.

start redis server on windows.

If you are using Mac OS X/Linux, you can use brew and execute the following.

$ brew update && brew install redis

Create Spring Boot application

Create a Spring boot application with required dependencies. Add spring-boot-starter-web, spring-boot-starter-data-redis, and Lombok dependencies to the pom.xml file of the Spring Boot application.

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>

Creating REST endpoints

Let us create the REST endpoints to perform CRUD operation with Redis.

Create an entity class

Create a Student.java class. This class is similar to the JPA entity class, which will get persisted in the Redis server. 

package com.asbnotebook.entity;

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

import lombok.Data;

@Data
@RedisHash(value = "student")
public class Student {

	@Id
	@Indexed
	private String id;
	private String name;
	private String grade;
}
  • @Data: Lombok annotation that provides the required constructor and getter/setter methods.
  • @RedisHash: The annotation marks objects as aggregate roots to be stored in a Redis hash.
  • @Id: Indicates that this is the Id field of the entity class.
  • @Indexed: Creates an index on Redis for the annotated field, which helps in improvised performance during retrieval of data.

Create repository layer

Similar to the JPA repositories, Spring boot provides built-in support for basic data operations for Redis as well.

Create a StudentRepository.java interface and extend CrudRepositroy to make use of the basic out of the box data functionalities provided by Spring Boot.

package com.asbnotebook.repository;

import org.springframework.data.repository.CrudRepository;

import com.asbnotebook.entity.Student;

public interface StudentRepository extends CrudRepository<Student, String> {

}

Create REST endpoints

Create a StudentController.java class.

This class will have all the CRUD endpoints required for our application.

Notice that we have auto wired the repository instance into the controller class and used available methods to perform the CRUD operation on our Student object.

package com.asbnotebook.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.asbnotebook.entity.Student;
import com.asbnotebook.repository.StudentRepository;

@RestController
public class StudentController {

	@Autowired
	private StudentRepository studentRepository;

	@PostMapping("/students")
	public ResponseEntity<Student> createStudent(@RequestBody Student student) {
		Student savedStudent = studentRepository.save(student);
		return new ResponseEntity<>(savedStudent, HttpStatus.CREATED);
	}

	@PutMapping("/student/{id}")
	public ResponseEntity<Student> updateStudent(@PathVariable(name = "id") String id, @RequestBody Student student) {
		Optional<Student> std = studentRepository.findById(id);
		if (std.isPresent()) {
			Student studentDB = std.get();
			studentDB.setGrade(student.getGrade());
			studentDB.setName(student.getName());
			Student updatedStudent = studentRepository.save(studentDB);
			return new ResponseEntity<>(updatedStudent, HttpStatus.CREATED);
		}
		return null;
	}

	@GetMapping("/students")
	public ResponseEntity<List<Student>> getStudents() {
		List<Student> students = new ArrayList<>();
		studentRepository.findAll().forEach(students::add);
		return new ResponseEntity<>(students, HttpStatus.OK);
	}

	@DeleteMapping("/student/{id}")
	public ResponseEntity<String> deleteStudent(@PathVariable(name = "id") String id) {
		studentRepository.deleteById(id);
		return new ResponseEntity<>("Student with id:" + id + " deleted successfully", HttpStatus.OK);
	}
}

Configuring Redis

Add the below Redis configurations to the spring Boot applications application.properties configuration file under the /src/main/resources/ directory.

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

Testing the CRUD operation

Run the Spring Boot application.

Create

Pass the student details bay passing the JSON request to the POST endpoint.

Spring boot redis crud example

We can notice that the Redis hash is created and saved inside the Redis server.

Spring boot redis crud example

Update

Send the JSON request object to the PUT method with an updated student name.

Spring boot redis crud example

Get

We can get all the available students in the Redis server by calling the GET endpoint.

Spring boot redis crud example

Delete

Pass the id to the DELETE endpoint to delete the student object, stored in the Redis server.

Spring boot redis crud example

Conclusion

In this example, we learned how to create a CRUD application using Spring Boot and Redis NoSQL database.

We also learned how spring-boot-starter-data-redis provides repository supports that can be used to perform basic CRUD operations.

Example code is available on GitHub.

You may also be interested in