0
0
Spring Bootframework~5 mins

Cache configuration in Spring Boot

Choose your learning style9 modes available
Introduction

Cache configuration helps your app remember data so it can work faster next time. It saves time by not repeating slow tasks.

When your app fetches data from a database many times and you want to speed it up.
When you call a slow external service and want to avoid calling it repeatedly.
When you want to reduce load on your server by storing results temporarily.
When you want to improve user experience by showing data faster.
When you want to control how long data stays saved before refreshing.
Syntax
Spring Boot
@EnableCaching
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("items");
    }
}

@EnableCaching turns on caching in your Spring Boot app.

CacheManager defines where and how cache is stored.

Examples
This example creates caches named 'books' and 'authors' using simple in-memory storage.
Spring Boot
@EnableCaching
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("books", "authors");
    }
}
This example shows another way to create a cache manager with a cache named 'users'.
Spring Boot
@EnableCaching
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager manager = new SimpleCacheManager();
        manager.setCaches(List.of(new ConcurrentMapCache("users")));
        return manager;
    }
}
Sample Program

This program sets up a cache named 'greetings'. The GreetingService method getGreeting simulates a slow call by waiting 2 seconds. The first call caches the result. The second call returns the cached greeting immediately, making it faster.

Spring Boot
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import java.util.List;

@EnableCaching
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("greetings");
    }
}

@Service
class GreetingService {

    @Cacheable("greetings")
    public String getGreeting(String name) {
        try {
            Thread.sleep(2000); // simulate slow method
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Hello, " + name + "!";
    }
}

// Usage example (e.g., in a Spring context with @Autowired GreetingService service):
// System.out.println(service.getGreeting("Alice")); // takes 2 seconds first time
// System.out.println(service.getGreeting("Alice")); // returns instantly from cache
OutputSuccess
Important Notes

Cache names must match between configuration and @Cacheable annotations.

Use caching only for data that does not change often or can be stale briefly.

Spring Boot supports many cache types like Redis, Ehcache, and simple memory caches.

Summary

Cache configuration speeds up apps by storing data temporarily.

Use @EnableCaching and define a CacheManager bean to set up caching.

Mark methods with @Cacheable to save their results automatically.