Redis helps your Spring Boot app remember data quickly. It stores data in memory so your app can get it fast without waiting for slow databases.
Redis as cache provider in Spring Boot
spring.cache.type=redis spring.redis.host=localhost spring.redis.port=6379 @EnableCaching @Configuration public class CacheConfig { @Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { return RedisCacheManager.builder(factory).build(); } }
Set Redis connection details in application.properties or application.yml.
Use @EnableCaching to activate caching in Spring Boot.
getBookById in Redis under the 'books' cache.@Cacheable("books")
public Book getBookById(Long id) {
// method logic
}@CacheEvict(value = "books", key = "#id") public void removeBookFromCache(Long id) { // method logic }
@CachePut(value = "books", key = "#book.id") public Book updateBook(Book book) { // method logic return book; }
This Spring Boot app uses Redis to cache book titles. The first call to getBookTitleById waits 3 seconds, but later calls return instantly from cache.
package com.example.cache; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.stereotype.Service; @SpringBootApplication @EnableCaching public class CacheApplication { public static void main(String[] args) { SpringApplication.run(CacheApplication.class, args); } @Configuration static class CacheConfig { @Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { return RedisCacheManager.builder(factory).build(); } } @Bean public CommandLineRunner demo(BookService bookService) { return args -> { System.out.println("Calling getBookTitleById(1) first time..."); String result1 = bookService.getBookTitleById(1L); System.out.println("Result: " + result1); System.out.println("Calling getBookTitleById(1) second time..."); String result2 = bookService.getBookTitleById(1L); System.out.println("Result: " + result2); }; } @Service static class BookService { @Cacheable("books") public String getBookTitleById(Long id) { simulateSlowService(); return "Book Title " + id; } private void simulateSlowService() { try { Thread.sleep(3000); // simulate delay } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } }
Make sure Redis server is running locally or update host/port accordingly.
Cached data stays in Redis until expired or evicted.
Use @Cacheable on methods that return data you want to cache.
Redis stores data in memory for fast access in Spring Boot apps.
Use @EnableCaching and RedisCacheManager to enable Redis caching.
Annotate methods with @Cacheable to cache their results automatically.
Practice
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 AQuick Check:
Redis cache = fast data access [OK]
- Thinking Redis replaces the database
- Confusing caching with authentication
- Assuming Redis serves static files
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 CQuick Check:
Enable caching = @EnableCaching [OK]
- Confusing @Cacheable with enabling caching
- Using non-existent @RedisCache annotation
- Mistaking @CacheConfig for enabling 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?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 AQuick Check:
Cache avoids repeated DB fetch print [OK]
- Expecting print on every call
- Thinking cache disables method
- Assuming runtime error due to caching
@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?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 DQuick Check:
Redis down usually does not crash app by default [OK]
- Assuming fallback to memory cache
- Thinking caching silently fails
- Expecting file-based fallback
public List<User> getUsersByRole(String role) {
// fetch users
}Solution
Step 1: Understand caching empty results issue
Caching empty or null results wastes cache space and may cause stale data.Step 2: Use @Cacheable condition attribute
Adding condition "#result != null && !#result.isEmpty()" caches only meaningful results.Final Answer:
Use @Cacheable with condition = "#result != null && !#result.isEmpty()" -> Option BQuick Check:
Condition filters empty cache entries [OK]
- Caching all results including empty lists
- Manually caching inside method instead of annotation
- Using @CachePut which always updates cache
Ready to prove it?
Pass the test and this pattern moves unknown
