How to Use Caffeine Cache in Spring Boot: Simple Guide
To use
Caffeine Cache in Spring Boot, add the spring-boot-starter-cache and caffeine dependencies, enable caching with @EnableCaching, and configure a CaffeineCacheManager. Then annotate methods with @Cacheable to cache their results automatically.Syntax
Here is the basic setup to use Caffeine cache in Spring Boot:
- Add dependencies for Spring Cache and Caffeine.
- Enable caching in your main application class with
@EnableCaching. - Configure a
CaffeineCacheManagerbean to customize cache settings. - Use
@Cacheableon methods whose results you want to cache.
java
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.github.benmanes.caffeine.cache.Caffeine; @Configuration @EnableCaching public class CacheConfig { @Bean public CaffeineCacheManager cacheManager() { CaffeineCacheManager cacheManager = new CaffeineCacheManager("items"); cacheManager.setCaffeine(Caffeine.newBuilder() .initialCapacity(100) .maximumSize(500) .expireAfterWrite(java.time.Duration.ofMinutes(10))); return cacheManager; } }
Example
This example shows a Spring Boot service caching method results using Caffeine. The getItemById method caches its return value for 10 minutes. The first call fetches data normally; subsequent calls return cached data instantly.
java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @SpringBootApplication public class CaffeineCacheApplication { public static void main(String[] args) { SpringApplication.run(CaffeineCacheApplication.class, args); } } @Service class ItemService { @Cacheable("items") public String getItemById(String id) { simulateSlowService(); return "Item-" + id; } private void simulateSlowService() { try { Thread.sleep(3000); // Simulate delay } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Output
First call to getItemById("123") takes ~3 seconds and returns "Item-123".
Subsequent calls to getItemById("123") return instantly with cached "Item-123".
Common Pitfalls
- Forgetting to add
@EnableCachingdisables caching. - Not configuring
CaffeineCacheManagerleads to default cache with no expiration. - Using inconsistent cache names between configuration and
@Cacheablecauses cache misses. - Caching methods with side effects or mutable return values can cause unexpected behavior.
java
/* Wrong: Missing @EnableCaching disables caching */ @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } /* Right: Add @EnableCaching to enable caching */ @SpringBootApplication @EnableCaching public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
Quick Reference
Summary tips for using Caffeine cache in Spring Boot:
- Add
spring-boot-starter-cacheandcom.github.ben-manes.caffeinedependencies. - Enable caching with
@EnableCaching. - Configure
CaffeineCacheManagerbean for cache size and expiry. - Use
@Cacheableon methods to cache results. - Ensure cache names match between config and annotations.
Key Takeaways
Add Caffeine and Spring Cache dependencies and enable caching with @EnableCaching.
Configure CaffeineCacheManager bean to control cache size and expiration.
Use @Cacheable on methods to cache their return values automatically.
Ensure cache names are consistent between configuration and annotations.
Avoid caching methods with side effects or mutable return values.