When you have 200 concurrent users hitting a single-threaded service, you’ll see the database queries pile up, causing significant delays and potentially leading to a system crash. This is where Redis caching comes in, allowing you to store frequently accessed data in memory for faster retrieval.
## PREREQUISITES To follow this tutorial, you’ll need: * Java 11 or later * Spring Boot 2.5 or later * Maven or Gradle * Redis 6 or later The following Maven dependency is required:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
## UNDERSTANDING REDIS CACHING Redis caching works by storing data in memory, allowing for faster access times compared to traditional database queries. Here’s an ASCII diagram illustrating the flow:
+---------------+ | Spring Boot | +---------------+ | | v +---------------+ | Redis Client | +---------------+ | | v +---------------+ | Redis Server | +---------------+
The following table compares Redis with other caching solutions:
| Caching Solution | Description |
|---|---|
| Redis | In-memory data store with pub/sub messaging and transactions |
| Ehcache | Java-based caching solution with support for distributed caching |
For further reading on caching solutions, visit our Spring Boot Tutorials page. ## STEP-BY-STEP IMPLEMENTATION ### Step 1: Set up Redis First, you need to set up a Redis instance. You can use a local Redis server or a cloud-based service like Redis Labs. ### Step 2: Configure Spring Boot to use Redis Next, you need to configure Spring Boot to use Redis as a cache. Add the following configuration to your `application.properties` file:
spring.redis.host=localhost spring.redis.port=6379 spring.redis.database=0
### Step 3: Implement caching for a sample service Create a sample service that uses Redis caching:
package com.example.app; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class SampleService { @Cacheable("sampleCache") public String getSampleData() { // simulate a database query try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Sample data"; } }
Expected output:
Sample data
## COMPLETE WORKING EXAMPLE Here’s a complete working example that ties everything together: * `SampleController.java`:
package com.example.app; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @Autowired private SampleService sampleService; @GetMapping("/sample") public String getSampleData() { return sampleService.getSampleData(); } }
* `SampleService.java`:
package com.example.app; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class SampleService { @Cacheable("sampleCache") public String getSampleData() { // simulate a database query try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return "Sample data"; } }
* `application.properties`:
spring.redis.host=localhost spring.redis.port=6379 spring.redis.database=0
Sample curl request: “`bash curl http://localhost:8080/sample “` Response:
Sample data
## COMMON MISTAKES AND HOW TO FIX THEM ### Mistake 1: Not closing the connection pool Bad code:
package com.example.app; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class SampleService { @Autowired private RedisTemplate<String, String> redisTemplate; public void getSampleData() { RedisConnection connection = redisTemplate.getConnection(); // use the connection // WRONG - causes connection leak } }
Error message:
java.lang.IllegalStateException: Connection is closed
Fixed code:
package com.example.app; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class SampleService { @Autowired private RedisTemplate<String, String> redisTemplate; public void getSampleData() { RedisConnection connection = redisTemplate.getConnection(); try { // use the connection } finally { connection.close(); } } }
For more information on Java Algorithms and data structures, visit our tutorials page. ## PERFORMANCE AND PRODUCTION TIPS
Production tip: Set
spring.redis.timeoutto a reasonable value (e.g., 5000) to avoid connection timeouts.
Production tip: Use a connection pool to manage Redis connections and improve performance.
For more information on Mastering SQL and database performance optimization, visit our tutorials page. ## TESTING Here’s an example JUnit 5 test for the `SampleService` class:
package com.example.app; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.cache.CacheManager; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith({SpringExtension.class, MockitoExtension.class}) public class SampleServiceTest { @InjectMocks private SampleService sampleService; @Test public void testGetSampleData() { // test the service String result = sampleService.getSampleData(); // assert the result org.junit.jupiter.api.Assertions.assertEquals("Sample data", result); } }
For more information on Spring Batch and batch processing, visit our tutorials page. ## KEY TAKEAWAYS * Use Redis caching to improve performance and reduce database queries * Configure Spring Boot to use Redis as a cache * Implement caching for services using the `@Cacheable` annotation * Use a connection pool to manage Redis connections * Set a reasonable timeout value for Redis connections * Test the caching implementation using JUnit 5 tests * Visit our More Java Tutorials page for more information on Java and Spring Boot. * Learn about SOLID Design Principles in Java to improve your coding skills. * Practice with Java Interview Questions to prepare for your next interview.
spring-boot-examples — Clone, Star & Contribute

Leave a Reply