📖 Scenario: You are building a Spring Boot application that fetches product details from a database. To improve performance, you want to use Redis as a cache provider so that repeated requests for the same product do not hit the database every time.
🎯 Goal: Build a Spring Boot application that uses Redis as a cache provider to store and retrieve product details efficiently.
📋 What You'll Learn
Create a simple Product class with id and name fields
Configure Redis cache manager in Spring Boot
Enable caching in the Spring Boot application
Use @Cacheable annotation on the method fetching product details
💡 Why This Matters
🌍 Real World
Caching with Redis is common in web applications to reduce database load and improve response times for frequently requested data.
💼 Career
Many backend developer roles require knowledge of caching strategies and integrating Redis with Spring Boot for scalable applications.
Progress0 / 4 steps
1
Create Product class
Create a Java record called Product with two fields: Long id and String name.
Spring Boot
Hint
A record is a simple way to create immutable data classes in Java 17+. Use the record keyword.
2
Enable caching and configure Redis
In your Spring Boot main application class, add the @EnableCaching annotation above the class declaration. Also, create a RedisCacheManager bean method named cacheManager that returns a default RedisCacheManager using RedisCacheManager.create(redisConnectionFactory). Assume redisConnectionFactory is injected as a method parameter.
Spring Boot
Hint
Use @EnableCaching on the main class to activate caching. Define a @Bean method returning RedisCacheManager.create(redisConnectionFactory).
3
Create ProductService with caching
Create a Spring service class called ProductService with a method getProductById(Long id) that returns a Product. Annotate this method with @Cacheable("products"). Inside the method, return a new Product with the given id and name as "Product" + id.
Spring Boot
Hint
Use @Cacheable("products") on the method to enable caching. Return a new Product with the id and name "Product" + id.
4
Use ProductService in a REST controller
Create a REST controller class called ProductController with a GET mapping /products/{id}. Inject ProductService and in the handler method getProduct(Long id), return the result of productService.getProductById(id). Annotate the class with @RestController and the method with @GetMapping("/products/{id}").
Spring Boot
Hint
Create a REST controller with a GET endpoint that calls the cached service method to return product details.
Practice
(1/5)
1. What is the main purpose of using Redis as a cache provider in a Spring Boot application?
easy
A. To store frequently accessed data in memory for faster retrieval
B. To replace the database completely
C. To handle user authentication
D. To serve static web pages
Solution
Step 1: Understand Redis caching role
Redis stores data in memory, which is much faster than disk storage.
Step 2: Identify caching benefit in Spring Boot
Caching reduces database calls by storing frequently used data temporarily.
Final Answer:
To store frequently accessed data in memory for faster retrieval -> Option A
Quick Check:
Redis cache = fast data access [OK]
Hint: Redis cache speeds up data access by storing in memory [OK]
Common Mistakes:
Thinking Redis replaces the database
Confusing caching with authentication
Assuming Redis serves static files
2. Which annotation is used in Spring Boot to enable caching support when using Redis?
easy
A. @RedisCache
B. @Cacheable
C. @EnableCaching
D. @CacheConfig
Solution
Step 1: Identify the annotation to activate caching
@EnableCaching is used on a configuration class to turn on caching support.
Step 2: Differentiate from other annotations
@Cacheable marks methods to cache results, but does not enable caching globally.
Final Answer:
@EnableCaching -> Option C
Quick Check:
Enable caching = @EnableCaching [OK]
Hint: Use @EnableCaching to activate caching in Spring Boot [OK]
Common Mistakes:
Confusing @Cacheable with enabling caching
Using non-existent @RedisCache annotation
Mistaking @CacheConfig for enabling caching
3. Given the following Spring Boot method with Redis caching:
@Cacheable("books")
public Book findBookById(Long id) {
System.out.println("Fetching from DB");
return bookRepository.findById(id).orElse(null);
}
What will be printed if findBookById(1L) is called twice in a row?
medium
A. Fetching from DB
B. No output
C. Fetching from DB
Fetching from DB
D. Error at runtime
Solution
Step 1: Understand @Cacheable behavior
The first call caches the result and prints "Fetching from DB".
Step 2: Analyze second call output
The second call returns cached data without executing method body, so no print.
Final Answer:
Fetching from DB -> Option A
Quick Check:
Cache avoids repeated DB fetch print [OK]
Hint: First call prints, second uses cache silently [OK]
Common Mistakes:
Expecting print on every call
Thinking cache disables method
Assuming runtime error due to caching
4. Consider this Spring Boot Redis cache configuration snippet:
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.builder(factory).build();
}
If the Redis server is down, what will happen when the application tries to cache data?
medium
A. Application falls back to file-based cache
B. Application throws a runtime exception and crashes
C. Data is cached in memory without Redis
D. Caching silently fails but application continues
Solution
Step 1: Understand RedisCacheManager dependency
RedisCacheManager requires a running Redis server to store cache data.
Step 2: Analyze behavior if Redis is down
Without Redis, cache operations typically fail silently and the application continues unless explicitly configured to fail.
Final Answer:
Caching silently fails but application continues -> Option D
Quick Check:
Redis down usually does not crash app by default [OK]
Hint: Redis down causes silent cache failure unless handled [OK]
Common Mistakes:
Assuming fallback to memory cache
Thinking caching silently fails
Expecting file-based fallback
5. You want to cache the result of a method that returns a list of users filtered by role. Which is the best way to use Redis caching in Spring Boot to avoid caching empty or null results?
public List<User> getUsersByRole(String role) {
// fetch users
}
hard
A. Use @CachePut to always update cache
B. Use @Cacheable with condition = "#result != null && !#result.isEmpty()"
C. Manually check and cache inside the method
D. Use @Cacheable without any condition
Solution
Step 1: Understand caching empty results issue
Caching empty or null results wastes cache space and may cause stale data.