Spring Boot 4 Microservices & REST APIs · Lekcja

TTL i unieważnianie cache

Zarządzaj wygasaniem i usuwaniem wpisów

Lekcja 4 z 413 kroki

TTL i unieważnianie cache to bezpłatna lekcja Spring Boot 4 Microservices & REST APIs na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Boot 4 Microservices & REST APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Why TTL Matters

Cached data can go stale. A TTL (time-to-live) automatically expires entries after a set duration, bounding how stale data can get.

Setting a Default TTL

Apply a TTL to all caches via the default configuration.

RedisCacheConfiguration config =
    RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofMinutes(10));

Per-Cache TTL

Different data ages at different rates — give each cache its own TTL.

Map<String, RedisCacheConfiguration> configs = Map.of(
    "products",
        RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofHours(1)),
    "prices",
        RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofMinutes(1)));

Caffeine TTL via Properties

For a local Caffeine cache, set expiry in properties.

spring.cache.caffeine.spec=expireAfterWrite=300s,maximumSize=1000

Explicit Invalidation

TTL handles time-based expiry; @CacheEvict handles event-based invalidation when data changes.

@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
    repository.deleteById(id);
}

Write-Through Updates

Pair an update with @CachePut so the cache reflects the new value immediately instead of waiting for expiry.

@CachePut(value = "products", key = "#product.id")
public Product update(Product product) {
    return repository.save(product);
}

Clearing a Whole Cache

After a bulk change, evict all entries to force fresh reads.

@CacheEvict(value = "products", allEntries = true)
public void importBatch(List<Product> items) {
    repository.saveAll(items);
}

Eviction Policies

When a cache hits its size limit, an eviction policy decides what to remove. Common policies: LRU (least recently used) and LFU (least frequently used).

Bounding Cache Size

Limit memory by capping the number of entries with Caffeine's maximumSize.

spring.cache.caffeine.spec=maximumSize=10000

Cache Stampede

When a popular key expires, many requests miss at once and all hit the database — a stampede. Mitigate with short staggered TTLs or refresh-ahead strategies.

Monitoring Hit Rate

Track the cache hit rate (hits ÷ total lookups). A low rate means the cache is not helping — revisit TTL, keys, or whether caching fits the access pattern.

Quick Check

Test your understanding of TTL and invalidation.

Recap

You learned cache expiry and invalidation:

  • TTL via entryTtl bounds staleness
  • Per-cache TTLs for different data
  • @CacheEvict / @CachePut for event-based invalidation
  • Eviction policies (LRU/LFU), size limits, and stampede awareness
Bezpłatny start

Ucz się Java dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
24
Lekcje
93

Często zadawane pytania

Czy lekcja „TTL i unieważnianie cache” jest bezpłatna?

Tak — pełny tekst „TTL i unieważnianie cache” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Boot 4 Microservices & REST APIs, przejdź na CoddyKit PRO. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.

Co nauczysz się w „TTL i unieważnianie cache”?

Zarządzaj wygasaniem i usuwaniem wpisów Ćwiczysz Spring Boot 4 Microservices & REST APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Spring Boot 4 Microservices & REST APIs?

Nie wymagamy żadnego doświadczenia. Spring Boot 4 Microservices & REST APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „TTL i unieważnianie cache”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Spring Boot 4 Microservices & REST APIs?

Tak. Każda lekcja Spring Boot 4 Microservices & REST APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Abstrakcja cache Spring
  2. @Cacheable, @CachePut, @CacheEvict
  3. Redis jako dostawca cache
  4. TTL i unieważnianie cache
← Powrót do Spring Boot 4 Microservices & REST APIs