
Play Store Application link β Spring Boot in 13 steps – App on Google Play
Github project link – https://github.com/kuldeep101990/Caching-in-Spring-Boot
Step 1: Setting Up a Spring Boot Project
Using Spring Initializr
- Visit https://start.spring.io/.
- Configure the project:
- Project: Maven
- Language: Java
- Spring Boot Version: 3.x.x
- Dependencies: Spring Web, Spring Cache, Spring Boot DevTools
- Click Generate to download the project ZIP and extract it.
Import into IDE
- Import the project into your favorite IDE (IntelliJ, Eclipse, etc.) as a Maven project.
Step 2: Enable Caching in Spring Boot
Add @EnableCaching
Enable caching in your Spring Boot application by annotating the main application class:
package com.example.cachingdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CachingDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CachingDemoApplication.class, args);
}
}
Step 3: Using Caching Annotations
Create a Service for Demonstration
package com.example.cachingdemo.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class CalculationService {
@Cacheable("squareCache")
public int calculateSquare(int number) {
simulateSlowService();
return number * number;
}
private void simulateSlowService() {
try {
Thread.sleep(3000); // Simulate delay
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Add a REST Controller
package com.example.cachingdemo.controller;
import com.example.cachingdemo.service.CalculationService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CalculationController {
private final CalculationService calculationService;
public CalculationController(CalculationService calculationService) {
this.calculationService = calculationService;
}
@GetMapping("/square")
public int getSquare(@RequestParam int number) {
return calculationService.calculateSquare(number);
}
}
Test the Caching
- Start the application.
- Access the endpoint:
http://localhost:8080/square?number=4
.- First request will take 3 seconds.
- Subsequent requests will be instant due to caching.
Step 4: Using @CacheEvict and @CachePut
Modify the Service
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
@Service
public class CalculationService {
@Cacheable("squareCache")
public int calculateSquare(int number) {
simulateSlowService();
return number * number;
}
@CachePut(value = "squareCache", key = "#number")
public int updateSquare(int number) {
return number * number;
}
@CacheEvict(value = "squareCache", allEntries = true)
public void clearCache() {
// Cache cleared
}
}
Step 5: Configuring Cache Providers
Option A: Using Ehcache
- Add Ehcache dependency to
pom.xml
:
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.10.8</version>
</dependency>
- Create
ehcache.xml
insrc/main/resources
:
<config xmlns="http://www.ehcache.org/v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd">
<cache alias="squareCache">
<key-type>java.lang.Integer</key-type>
<value-type>java.lang.Integer</value-type>
<heap unit="entries">100</heap>
</cache>
</config>
- Add Ehcache configuration to
application.properties
:
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml
Option B: Using Redis
- Add Redis dependencies to
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- Add Redis configuration to
application.properties
:
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
- Run Redis server locally or using Docker:
docker run --name redis -p 6379:6379 -d redis
Conclusion
In this guide, we covered:
- Enabling caching in Spring Boot.
- Using
@Cacheable
,@CacheEvict
, and@CachePut
annotations. - Configuring cache providers like Ehcache and Redis.