Fix Micronaut @Cacheable Not Caching
In this tutorial, you'll learn about Fix Micronaut @Cacheable Not Caching. We cover key concepts, practical examples, and best practices.
The Problem
Method results annotated with @Cacheable are not cached. Each invocation executes the method again.
Quick Fix
Add cache dependency
Wrong:
<!-- No cache -->
Output:
No caching support
Right:
<dependency>
<groupId>io.micronaut.cache</groupId>
<artifactId>micronaut-cache-core</artifactId>
</dependency>
Output:
Caching enabled
Configure cache implementation
Wrong:
# No cache config
micronaut.cache.type=caffeine
Output:
No cache backend
Right:
micronaut:
cache:
type: caffeine
caffeine:
max-size: 1000
Output:
Caffeine cache configured
Use @Cacheable correctly
Wrong:
@Cacheable("products")
public Product getProduct(Long id) { return expensiveCall(); }
Output:
Cached correctly
Right:
@Cacheable("products")
public Product getProduct(Long id) {
return expensiveCall();
}
Output:
Result cached after first call
Prevention
- Add micronaut-cache-core dependency
- Configure cache type (caffeine, redis, etc.)
- Use @Cacheable on methods that should be cached
Common Mistakes with cache
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations
These mistakes appear frequently in real-world MICRONAUT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
This quick fix is part of the DodaTech Spring & JVM ecosystem series. Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro