0Pricing
Spring Boot 4 Microservices & REST APIs · Урок

@Cacheable, @CachePut, @CacheEvict

Точно управляйте поведением кэша

«@Cacheable, @CachePut, @CacheEvict» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

The Three Cache Annotations

Spring offers three method-level cache annotations:

  • @Cacheable — read-through, store the result
  • @CachePut — always run, update the cache
  • @CacheEvict — remove entries

@Cacheable

@Cacheable checks the cache first; on a miss it runs the method and stores the result.

@Cacheable("products")
public Product findById(Long id) {
    return repository.findById(id).orElseThrow();
}

Conditional Caching

Use condition to cache only when a predicate holds, and unless to skip caching certain results.

@Cacheable(value = "products",
    unless = "#result == null")
public Product findById(Long id) { ... }

@CachePut

@CachePut always executes the method and stores the returned value — ideal for update methods that should refresh the cache.

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

Cacheable vs CachePut

@Cacheable may skip the method on a hit; @CachePut never skips. Never put both on the same method — their behaviors conflict.

@CacheEvict

@CacheEvict removes an entry, typically after a delete or update that invalidates cached data.

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

Evicting Everything

Use allEntries = true to clear an entire cache at once.

@CacheEvict(value = "products", allEntries = true)
public void reloadAll() {
    // bulk refresh
}

Evict Before or After

By default eviction happens after the method succeeds. Set beforeInvocation = true to evict even if the method throws.

@CacheEvict(value = "products",
    allEntries = true, beforeInvocation = true)
public void risky() { ... }

Grouping with @Caching

@Caching combines multiple cache operations on one method.

@Caching(
    put = @CachePut(value = "products", key = "#p.id"),
    evict = @CacheEvict(value = "productList",
        allEntries = true))
public Product save(Product p) {
    return repository.save(p);
}

Class-Level Config

@CacheConfig sets a default cache name for all methods in a class, reducing repetition.

@Service
@CacheConfig(cacheNames = "products")
public class ProductService {
    @Cacheable(key = "#id")
    public Product findById(Long id) { ... }
}

Self-Invocation Caveat

Cache annotations work via proxies, so a method calling another cached method in the same class bypasses the cache. Call through a separate bean.

Quick Check

Test your understanding of the cache annotations.

Recap

You learned the three cache annotations:

  • @Cacheable — store and reuse results
  • @CachePut — always run and refresh
  • @CacheEvict — remove entries (allEntries, beforeInvocation)
  • Watch out for the self-invocation proxy caveat

Часто задаваемые вопросы

Урок «@Cacheable, @CachePut, @CacheEvict» бесплатный?

Да — полный текст урока «@Cacheable, @CachePut, @CacheEvict» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Чему я научусь в уроке «@Cacheable, @CachePut, @CacheEvict»?

Точно управляйте поведением кэша Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «@Cacheable, @CachePut, @CacheEvict»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Абстракция кэширования Spring
  2. @Cacheable, @CachePut, @CacheEvict
  3. Redis как провайдер кэша
  4. TTL кэша и инвалидация
← Назад к Spring Boot 4 Microservices & REST APIs