AroundAround
Sign in Sign up
Menu
  • Home
    • Home
  • Blog
    Technology
    All Technology Software Engineering Web Applications Java Spring Framework Spring Boot AWS
    All Posts
    Smash Posts Transportation Posts Driving Posts Multi Location Post
    Transport
    Driving Articles Driving License Resources Refresh Drive Success Stories Special Articles
    Research
    Popular lists Weblogs Tutorials
    News
    Education Health Sports
    Traffic Signs
    Dubai Traffic Signs Qatar Traffic Signs Abu Dhabi Traffic Signs Saudi Arabia Traffic Signs Kuwait Traffic Signs Kerala Traffic Signs
  • Insights
    Interview Series
    All Interview Series Java Questions Spring Questions Microservices Questions Database Questions
    Lifestyle
    Umrah Articles Dubai UAE visa 180 days calculator Qatar residence visa 180 days calculator Prayer Time Malappuram Sqm to Cent calculator Kerala
    City Explorer
    Sulthan Bathery
  • Mock Tests
    Driving
    Test Home
    Dubai
    RTA Theory Test Parking Knowledge Test Deep-dive Assessment Test
    Abu Dhabi
    RTA Driving Theory Test Deep-dive Assessment Test Saudi Arabia Computer Test
    Other Regions
    Qatar Driving Theory Test Kuwait Driving Theory Test Ajman RTA Theory Test Sharjah RTA Theory Test Bahrain Driving Theory Test Learners License Test - Kerala
    Education
    Kindergarten School
  • Course & Videos
    • CoursesEnroll today
    • Videos20+Watch & Subscribe
  • Questions and Tags
    Topics
    Don't miss Million dollar questions Million Views Day to day life Interview Junky Trendy questions Theory wizard
    Technology
    Java Spring AWS
    Find the differences
    All Find the differences List
    Tags
    macOS AWS Spring
  • About Us
    • Privacy Policy
    • Contact
    • Terms & Conditions
    • Cancellation & Refund Policy
    • Shipping & Delivery Policy
  1. Home
  2. java
  3. Post

Caching TTL for @Cacheable annotation

Emma Brown
admin
#java #programming
Share post:
Share

Spring's `@Cacheable` got you down? Tired of manual TTL implementations with `@CacheEvict` and `@Scheduled`? There's a simpler way... Find out how!

Spring 3.1's `@Cacheable`: Can I set a TTL for cached data? Manually clearing with `@CacheEvict` and `@Scheduled` seems excessive. Is there a simpler way?

Solution in a Nutshell

Setting Cache TTL in Spring Boot

Spring's @Cacheable doesn't directly support TTL. You manage TTL indirectly using CacheEviction. Several strategies exist:

1. Using @Scheduled for periodic eviction:

This approach evicts cached entries after a fixed time. Define a @Scheduled task to remove entries based on entry creation time (e.g., using a custom key).

@Scheduled(fixedRate = 3600000) // Evict every hour
public void evictExpiredEntries() {
    // Logic to find and evict entries older than 1 hour
    // Requires storing creation timestamp within cache key or value
}

2. Custom Cache Manager with Expiring Cache:

Create a custom CacheManager implementing Cache with expiration logic. This offers more fine-grained control.

public class ExpiringCache implements Cache {
    // ... (Implementation with expiry logic using java.util.concurrent.ConcurrentHashMap) ...
}

Register this custom CacheManager in your Spring configuration.

3. Using a dedicated caching library:

Libraries like Caffeine offer built-in TTL functionality. Integrate this library with Spring's caching abstraction. This is often the simplest and most efficient approach.

Example (Caffeine):

@Configuration
public class CacheConfig {
    @Bean
    public CaffeineCache caffeineCache() {
        return CaffeineCacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(3600, TimeUnit.SECONDS) // 1 hour TTL
                .build();
    }
}

Choose the method best suited to your needs. For simple scenarios, @Scheduled with careful key design suffices. Complex requirements benefit from a custom cache manager or dedicated libraries like Caffeine for superior performance and features. Remember to adjust fixedRate and expireAfterWrite values according to your specific TTL needs.

Sidebar

Search

Related

Post

`instanceof` null check needed?

Post

Isqrt Integer Check

Post

Java Array Concatenation

Post

File I/O: Create and Write

Tags

#java #programming

Trending posts

Post

How to iterate through the HashMap in Java?

Post

How Can I convert a String to an int in Java?

Post

How to get a key from the value in Java HashMap

Post

In javascript how to replace all occurrences of a String?

  • Contact Us
  • Privacy Policy

© Copyright - smashplus 2013-25.