Spring Data Redis Tutorial
author : Sai K
Spring Data Redis provides easy configuration and access to Redis from Spring applications. Redis is
an in
-memory data store often used as a database, cache, and message broker. In this tutorial, we
will cover how to
set up and use Spring Data Redis in a Spring Boot application.
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
- Go to Spring Initializrto create a new project with the following configuration:
- Select
- 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 store and retrieve data.
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
If you have Docker installed, you can run Redis using the following command:
docker run --name redis -d -p 6379:6379 redis
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
redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return template; } } Explanation:
- RedisTemplate
: Provides high-level abstractions for Redis interactions. - StringRedisSerializer: Serializes keys as strings.
- GenericJackson2JsonRedisSerializer: Serializes values as JSON using Jackson.
Step 4: Create a Redis Repository
Create a repository interface named UserRepository 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.User; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends CrudRepository
{ } Step 5: Create a User Model
Create a model class named User in the com.example.redis.model package.
package com.example.redis.model; import java.io.Serializable; public class User implements Serializable { private String id; private String name; private int age; public User() { } public User(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 6: Create a Service Classs
Create a service class named UserService in the com.example.redis.service package.
package com.example.redis.service; import com.example.redis.model.User; import com.example.redis.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; public User saveUser(User user) { return userRepository.save(user); } public Optional
getUserById(String id) { return userRepository.findById(id); } public Iterable getAllUsers() { return userRepository.findAll(); } public void deleteUserById(String id) { userRepository.deleteById(id); } } Step 7: Create a REST Controller
Create a controller class named UserController in the com.example.redis.controller package.
package com.example.redis.controller; import com.example.redis.model.User; import com.example.redis.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Optional; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @PostMapping public User saveUser(@RequestBody User user) { return userService.saveUser(user); } @GetMapping("/{id}") public Optional
getUserById(@PathVariable String id) { return userService.getUserById(id); } @GetMapping public Iterable getAllUsers() { return userService.getAllUsers(); } @DeleteMapping("/{id}") public void deleteUserById(@PathVariable String id) { userService.deleteUserById(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 Redis Operations
Use a tool like Postman or curl to test the endpoints.
1.Create a User:
- URL: http://localhost:8080/users
- Method: POST
- Body:
{ "id": "1", "name": "Ramesh Fadatare", "age": 30 }
2.Get a User by ID:
- URL: http://localhost:8080/users/1
- Method: GET
3.Get All Users:
- URL: http://localhost:8080/users
- Method: GET
4.Delete a User by ID:
- URL: http://localhost:8080/users/1
- Method: DELETE
You should see the correct responses and verify that the data is stored and retrieved from Redis.
Conclusion
In this tutorial, you have learned how to set up and use Spring Data Redis in a Spring Boot application. We
covered:- Setting up a Spring Boot project with Redis dependencies.
- Running Redis locally using Docker.
- Configuring Redis in Spring Boot.
- Creating a Redis repository and a model.
- Creating a service and a REST controller to interact with Redis.
- Testing the application to verify Redis operations.
By following these steps, you can leverage Redis to improve the performance and scalability of your Spring
Boot applications. - RedisTemplate