CacheManager
interface. This tutorial will guide you through using CacheManager
in a real-time scenario where we fetch user details from a remote API and cache the results to enhance performance.Prerequisites
- JDK 17 or later
- Maven or Gradle
- Spring Boot (version 3.2+ recommended)
- An API that provides user details (we'll use a mock service for this example)
- IDE (IntelliJ IDEA, Eclipse, etc.)
Step 1: Set Up a Spring Boot Project
Use Spring Initializr to create a new project with the following configuration:
- Project: Maven Project
- Language: Java
- Spring Boot: 3.2.x
- Dependencies: Spring Web, Spring Cache, Spring Boot DevTools
Download and unzip the project, then open it in your IDE.
Example Spring Boot Application
Create a Spring Boot application that fetches user details from a remote API and caches the results.
1.1 Application Class
package com.example.cachemanager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CacheManagerApplication {
public static void main(String[] args) {
SpringApplication.run(CacheManagerApplication.class, args);
}
}
1.2 Enable Caching
Enable caching by adding the @EnableCaching
annotation to your main application class.
package com.example.cachemanager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CacheManagerApplication {
public static void main(String[] args) {
SpringApplication.run(CacheManagerApplication.class, args);
}
}
1.3 Create a User Service with Caching
Create a service class named UserService
in the com.example.cachemanager.service
package. This service will fetch user details from a remote API and cache the results.
package com.example.cachemanager.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class UserService {
private final RestTemplate restTemplate = new RestTemplate();
@Cacheable("users")
public String getUserDetails(String userId) {
// Simulate a remote API call
String url = "https://jsonplaceholder.typicode.com/users/" + userId;
return restTemplate.getForObject(url, String.class);
}
}
Explanation:
@Cacheable("users")
: Caches the result of thegetUserDetails
method. The cache is identified by the name "users".
1.4 Create a REST Controller
Create a controller class named UserController
in the com.example.cachemanager.controller
package.
package com.example.cachemanager.controller;
import com.example.cachemanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users/{userId}")
public String getUserDetails(@PathVariable String userId) {
return userService.getUserDetails(userId);
}
}
1.5 Configure Cache Manager
You can configure the CacheManager
bean to customize your caching setup. Create a configuration class named CacheConfig
in the com.example.cachemanager.config
package.
package com.example.cachemanager.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("users");
}
}
Explanation:
@Configuration
: Indicates that the class declares one or more@Bean
methods.@EnableCaching
: Enables Spring’s annotation-driven cache management capability.ConcurrentMapCacheManager
: A simple implementation ofCacheManager
backed by aConcurrentHashMap
.
1.6 application.properties
Configuration
You can also configure some caching properties in the src/main/resources/application.properties
file.
# src/main/resources/application.properties
# Enable caching in Spring Boot (enabled by default with @EnableCaching)
spring.cache.type=simple
Step 2: Test the Application
2.1 Run the Application
Run the Spring Boot application using your IDE or the command line:
./mvnw spring-boot:run
2.2 Verify Caching Behavior
Open a web browser or a tool like Postman and navigate to the following URL to test the caching:
-
Initial Request:
- URL:
http://localhost:8080/users/1
- Method:
GET
- Response: (JSON response from the mock API, e.g., details of user 1)
- Time taken: A few seconds (simulating a remote API call)
- URL:
-
Subsequent Request:
- URL:
http://localhost:8080/users/1
- Method:
GET
- Response: (JSON response from the mock API, same as above)
- Time taken: Instant (result is retrieved from the cache)
- URL:
You should notice that the first request takes a few seconds, but subsequent requests for the same user ID return instantly, demonstrating that the result is being cached.
Conclusion
In this real-time example, you have learned how to use CacheManager
in Spring Boot to manage caching for a service that fetches user details from a remote API. We covered:
- Setting up a Spring Boot project with caching dependencies.
- Enabling caching in the application.
- Creating a service with caching to fetch user details.
- Creating a REST controller to expose the cached data.
- Configuring a simple
CacheManager
. - Testing the caching behavior.
By following these steps, you can effectively use caching to optimize the performance of your Spring Boot applications, reducing the load on external APIs and improving response times.
Comments
Post a Comment
Leave Comment