Spring Data Redis CRUD Example

Redis is a key-value store that can be used for multiple purposes. We can use Redis as a database, message broker, and cache. Spring provides built-in support for data operations, by providing Repository interfaces, that can be used for different data-related operations. Also, with the help of the spring data redis starter dependency, creating a CRUD application is an easy task.

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

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

Version details:

  • 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 from here.

Also, 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 data redis crud 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 the CRUD operations with Redis.

Create an entity class

Create a java class with the name Student. Also, 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 an interface with the name StudentRepository, 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

Now, create a java class with the name StudentController.

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

Also, 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 by passing the JSON request to the POST endpoint.

Spring boot redis crud example

Finally, we can notice that the Redis hash in the Redis server, as shown below.

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

Finally, the example code is available on GitHub.