0
0
Spring Bootframework~5 mins

Why caching matters for performance in Spring Boot

Choose your learning style9 modes available
Introduction

Caching helps your app work faster by saving results of slow tasks. It avoids doing the same work again and again.

When your app fetches data from a slow database multiple times.
When you call an external service that takes time to respond.
When you do heavy calculations that don't change often.
When you want to reduce load on your servers during peak times.
When you want users to get quick responses on repeated requests.
Syntax
Spring Boot
@Cacheable("cacheName")
public ReturnType methodName(Parameters) {
    // method logic
}
Use @Cacheable on methods whose results you want to save.
The cacheName is a label to group cached data.
Examples
This caches the book found by its ID so next calls with the same ID are faster.
Spring Boot
@Cacheable("books")
public Book findBookById(Long id) {
    // fetch book from database
}
This caches the price calculation result for each product.
Spring Boot
@Cacheable("prices")
public double calculatePrice(Product product) {
    // heavy price calculation
}
Sample Program

This service method simulates a slow operation by waiting 3 seconds. Using @Cacheable caches the result so repeated calls with the same key are fast.

Spring Boot
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class DataService {

    @Cacheable("dataCache")
    public String getData(String key) {
        try {
            Thread.sleep(3000); // simulate slow call
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Data for " + key;
    }
}

// Usage example in a Spring Boot app:
// Calling getData("test") first time takes 3 seconds.
// Calling getData("test") again returns instantly from cache.
OutputSuccess
Important Notes

Remember to enable caching in your Spring Boot app with @EnableCaching annotation.

Caches store data in memory by default, so be mindful of memory limits.

Cache keys are based on method parameters by default.

Summary

Caching saves time by reusing previous results.

Use @Cacheable on methods that do slow or repeated work.

Enable caching in your app to see performance improvements.