Удаление и истечение срока действия данных в кэше
Освойте методы управления размером кэша, настройки времени истечения (TTL) и обработки недействительности данных в кэше.
«Удаление и истечение срока действия данных в кэше» — бесплатный урок Redis Caching & Messaging (Pub/Sub, Streams) на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Redis Caching & Messaging (Pub/Sub, Streams), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Redis Caching & Messaging (Pub/Sub, Streams) содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Cache Expiration Matters
Caching is great for speed, but cached data can become stale, meaning it no longer reflects the true source of information. Also, caches have limited memory.
This lesson explores how to manage these issues using expiration and eviction techniques in Redis.
Introducing Time To Live (TTL)
Time To Live (TTL) defines how long a cached item remains valid. Once its TTL expires, Redis automatically removes the key.
- Prevents stale data from being served indefinitely.
- Frees up memory for newer, more relevant data.
Setting TTL with EXPIRE
The EXPIRE command sets an expiration time, in seconds, on an existing key. After the set time, the key will be automatically deleted.
Try setting a key and then giving it a 10-second expiration:
SET myapp:user:1 "John Doe"
EXPIRE myapp:user:1 10
TTL myapp:user:1SETEX: Set and Expire Together
Instead of two commands (SET then EXPIRE), you can use SETEX to set a key's value and its expiration time atomically (in one go).
This is generally preferred for new keys as it's more efficient.
SETEX myapp:product:5 20 "LaptopX"
TTL myapp:product:5Checking TTL & Persistence
You can check a key's remaining TTL with the TTL command. It returns the remaining seconds, or -2 if the key doesn't exist, -1 if it exists but has no expiration.
The PERSIST command removes the expiration from a key, making it permanent again.
SET temp:token "abc123"
EXPIRE temp:token 5
TTL temp:token
PERSIST temp:token
TTL temp:tokenMillisecond Precision with PEXPIRE
For more precise control, PEXPIRE and PSETEX work just like their second-based counterparts, but accept expiration times in milliseconds.
This can be useful for very short-lived caches or specific timing requirements.
SET mskey:data "important info"
PEXPIRE mskey:data 5000
PTTL mskey:dataAutomatic Eviction Policies
What happens when your Redis cache runs out of memory? Redis can be configured to automatically evict (remove) keys to free up space.
This behavior is controlled by the maxmemory setting and an eviction policy.
Common Eviction Policies
Redis offers several eviction policies configured via maxmemory-policy:
noeviction: Returns errors on write operations when memory limit is reached.allkeys-lru: Evicts least recently used (LRU) keys from all keys.volatile-lru: Evicts LRU keys *only* from those with an explicit TTL set.allkeys-random: Evicts random keys from all keys.
Manual Cache Invalidation
Sometimes, data changes unexpectedly, or you need to ensure a cache entry is immediately removed. In such cases, you can manually invalidate a key.
The DEL command removes one or more specified keys from Redis immediately.
SET cache:user:1 "user_data_old"
GET cache:user:1
DEL cache:user:1
GET cache:user:1Quick Check: Expiration
You have a Redis key named session:user:123. You want it to expire in exactly 30 minutes from now. Which command would achieve this?
Recap: Eviction & Expiration
In this lesson, you mastered key techniques for managing cached data in Redis:
- Using
EXPIRE,SETEX, andPEXPIREto set time-based expirations. - Understanding
TTLandPERSISTto manage key lifetimes. - Learning about automatic eviction policies to handle memory limits.
- Implementing manual cache invalidation with
DELfor immediate updates.
These skills are crucial for maintaining fresh data and efficient memory usage in your Redis cache!
Часто задаваемые вопросы
Урок «Удаление и истечение срока действия данных в кэше» бесплатный?
Да — полный текст урока «Удаление и истечение срока действия данных в кэше» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Redis Caching & Messaging (Pub/Sub, Streams), подпишись на CoddyKit PRO. Курс Redis Caching & Messaging (Pub/Sub, Streams) содержит 4 уроков всего.
Чему я научусь в уроке «Удаление и истечение срока действия данных в кэше»?
Освойте методы управления размером кэша, настройки времени истечения (TTL) и обработки недействительности данных в кэше. Ты практикуешь Redis Caching & Messaging (Pub/Sub, Streams) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Redis Caching & Messaging (Pub/Sub, Streams)?
Предыдущий опыт не требуется. Redis Caching & Messaging (Pub/Sub, Streams) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Удаление и истечение срока действия данных в кэше»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Redis Caching & Messaging (Pub/Sub, Streams)?
Да. Каждый урок Redis Caching & Messaging (Pub/Sub, Streams) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Зачем нужен кэш? Введение в кэширование
- Реализация базовых шаблонов кэширования
- Удаление и истечение срока действия данных в кэше
- Предотвращение лавинного обновления кэша