Introduction
In today’s world, fast and responsive applications are important. One easy and effective way to speed up our spring boot application using Redis. Redis acts as a high-performance cache and in-memory data store. In this blog, We will display you the way Redis could make a big difference on your Spring Boot packages. We will manual you through the setup procedure and explain to you how to use Redis and improve the performance of the packages. Whether you’re handling slow database queries or want to deal with extra users efficiently, Redis can help you achieve your dreams.
Prerequisites
- JDK 11 or Later
- Maven or Gradle
- Spring Boot Development Environment (Here we use IntelliJ IDEA)
- Redis Server(You can install Redis locally or use a cloud-based solution like Redis Labs)
What is Redis?
Redis, which stands for Remote Dictionary Server, is an open-source, in-memory data store. This makes it super quick for applications to access frequently used data, significantly speeding up performance. Redis is mainly used as a cache, meaning it stores data temporarily so apps can retrieve it faster without having to check the database every time.
Redis is a versatile tool that can be used for many different purposes, including
- Caching : It stores frequently accessed data, which reduces the load on the database and helps improve application performance.
- Session Management : Redis keeps track of user session data for web applications, ensuring a smooth user experience.
- Real-Time Analytics : It handles high-speed data operations, making it ideal for real-time analytics and processing.
- Message Brokering : Redis facilitates communication between different parts of an application, allowing for efficient message passing and coordination.
Why Use Redis?
Redis is a powerful tool for enhancing application performance, and there are several reasons why it’s a popular choice for developers:
- Speed : Redis operates in memory, making data retrieval extremely fast.
- Scalability : It can handle a large number of read and write operations, making it suitable for high-traffic applications.
- Versatility : Redis supports various data structures like strings, hashes, lists, sets, and more.
- Ease of Use : It integrates seamlessly with Spring Boot and other frameworks, simplifying the development process.
- Reliability : Redis offers persistence options, ensuring data durability even in case of failures.
How to Integrate Redis with a Spring Boot Application
Step 1 : Add Redis Dependency
If you’re using Maven, add the following dependencies to your pom.xml file:
org.springframework.boot
spring-boot-starter-data-redis
Step 2 : Configure Redis
You can configure Redis properties in your application.properties or application.yml file:
spring.redis.host=localhost
spring.redis.port=6379
Step 3 : Create a Redis Configuration Class
You can create a configuration class to customize the Redis template and connection factory:
@Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
Step 4 : Use Redis in Your Service
Now, you can inject the RedisTemplate into your service classes and use it to perform caching or other operations. Here’s an example of caching user data:
Adding a new User to Redis Cache and Database
The add method performs two key operations: saving a new user to the MySQL database and caching the user in Redis for quick access in future requests.
private static final String USER = "user:";
private final UserRepository userRepository;
private final RedisTemplate redisTemplate;
public UserServiceImpl(UserRepository userRepository,
RedisTemplate redisTemplate) {
this.userRepository = userRepository;
this.redisTemplate = redisTemplate;
}
@Override
public User add(User user) {
// Save user to MySQL
User savedUser = userRepository.save(user);
// Adding the saved user to the Redis cache
redisTemplate.opsForValue().set(USER + savedUser.getUserId(), savedUser);
return savedUser;
}
Add new User API
- To insert new customer data, select the POST method and send a request to http://localhost:8080/user/add, choosing Body > raw > JSON to include the customer data in JSON format.

Database view of Customer Data into Redis Database.
- redis-cli – To open the Redis interface
- KEYS user:* – To get all KEYS associated with Users.

Fetching a User by ID from Cache and Database
In this step, we optimize user retrieval by first checking Redis cache. If the user isn’t found in Redis, we fall back to the MySQL database and cache the result for future requests.
@Override
public User getAllById(Long userId) {
// Try to get user from Redis cache
User user = (User) redisTemplate.opsForValue().get(USER + userId);
log.info("Getting data for cache {}",user.getUserId());
// If not found in cache, retrieve from MySQL and store in Redis
if (user == null) {
user = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
redisTemplate.opsForValue().set(USER + userId, user);
}
return user;
}
Database view of Customer Data into Redis Database.
- redis-cli – To open the Redis interface
- KEYS Customer:* – To get all KEYS associated with Customer
- GET user:13 – Get User Data associated with id-13.

The log output shows whether the data is retrieved from Redis or MySQL. If found in Redis, a log confirms it; otherwise, a log indicates fetching from MySQL, followed by caching the result in Redis.

Deleting a User
In Redis, after removing data, you can verify its deletion by attempting to retrieve the same key and observing a null or “nil” result. Here’s how you can explain this in your blog:
@Override
public void delete(Long userId) {
// Find user in the database
User existUser = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User-id not found"));
// Mark user as deleted by setting the isDeleted flag
existUser.setIsDeleted(Boolean.TRUE);
// Save the updated user status in the database
userRepository.save(existUser);
// Remove user data from Redis cache
redisTemplate.delete(USER + userId);
}
Delete User API
- To delete a user with ID 12, send a DELETE request to the URL http://localhost:8080/user/delete/12.

Before deletion, executing GET user:12 retrieves the user’s data from Redis. After deletion, the same command returns (nil) or null, confirming that the data has been removed.

Updating User Information
The update process involves modifying the user’s details in both the MySQL database and the Redis cache to ensure data consistency.
@Override
public User update(Long userId, User user) {
// Find the existing user in the database
User existUser = userRepository.findById(userId)
.orElseThrow(() -> new RuntimeException("User not found"));
// Update user details
existUser.setFirstName(user.getFirstName());
existUser.setEmail(user.getEmail());
existUser.setLastName(user.getLastName());
existUser.setPhoneNumber(user.getPhoneNumber());
// Save the updated user in the database
User updatedUser = userRepository.save(existUser);
// Update the user data in Redis cache
redisTemplate.opsForValue().set(USER + updatedUser.getUserId(), updatedUser);
return updatedUser;
}
When the update method is executed, it retrieves the user from the database, and if found, it modifies the user’s details, such as first name and email. After saving the updated user back to MySQL, the Redis cache is refreshed with the new information, ensuring that subsequent requests retrieve the most current user data.

Conclusion
In this blog, we validated how to integrate Redis with the Spring Boot application and keep statistics in reminiscence. We use Redis to speak with the Spring Boot application, which improves boot efficiency by decreasing database load and improving data retrieval. Redis makes database queries greater efficient and person-pleasant, It can help to achieve our performance goal. Not best Redis is rapid and scalable, but also helps diverse information structures and use instances inclusive of caching, consultation control, actual-time analytics, and message brokering. Redis is a smooth device for integrating with Spring Boot making it critical for any developer seeking to improve software’s overall performance.