Redis 中的 TTL 与过期
了解 Redis 如何处理键过期:设置 TTL、使用 EXPIRE 和 SETEX 命令、懒惰过期与主动过期的工作方式,以及 maxmemory 驱逐策略如何与 TTL 交互。
Redis 中的 TTL 与过期 是 CoddyKit 上的免费 Caching Strategies: Redis + CDN + Edge Computing 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Caching Strategies: Redis + CDN + Edge Computing 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Caching Strategies: Redis + CDN + Edge Computing 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Expire Cache Keys?
Cached data goes stale. Time To Live (TTL) lets Redis automatically remove a key after a set duration, so your cache stays reasonably fresh without manual cleanup.
Setting a TTL with EXPIRE
The EXPIRE command sets a timeout in seconds on an existing key. After that time, Redis deletes the key automatically.
SET user:1 "Alice"
EXPIRE user:1 60
TTL user:1SET with EX in One Step
You can set a value and its TTL together. SET key value EX seconds (or the older SETEX) avoids a race between writing and expiring.
SET session:abc "data" EX 300Checking Remaining TTL
The TTL command returns seconds left. PTTL returns milliseconds. Special return values matter:
-1: key exists but has no expiry-2: key does not exist
def interpret_ttl(value):
if value == -1:
return 'no expiry set'
if value == -2:
return 'key does not exist'
return str(value) + 's remaining'
print(interpret_ttl(-2))
print(interpret_ttl(45))Removing an Expiry
The PERSIST command removes the TTL from a key, making it permanent again. Useful when a value should stop expiring after some condition is met.
PERSIST user:1Lazy Expiration
Redis does not check every key constantly. With lazy expiry, an expired key is only removed when someone tries to access it. Until then it lingers in memory.
Active Expiration
To reclaim memory from keys nobody touches, Redis also runs a background sampler that periodically removes a batch of expired keys. This is active expiry. Together with lazy expiry it keeps memory in check.
TTL vs Eviction
TTL is voluntary removal at a set time. Eviction happens when Redis hits its maxmemory limit and must drop keys to make room. They are different mechanisms that often work together.
volatile vs allkeys Policies
Eviction policies decide what to drop under memory pressure:
volatile-lru: evict least-recently-used keys that have a TTLallkeys-lru: evict LRU among all keys
For a pure cache, allkeys policies are common.
Choosing TTL Values
Pick TTLs from the data's tolerance for staleness: seconds for fast-changing prices, hours for catalogs, days for rarely-changing config. Add jitter to avoid synchronized mass expiry.
import random
base = 3600
print('TTL:', base + random.randint(0, 300), 'seconds')Common Pitfall: No TTL
Forgetting to set a TTL turns a cache into an ever-growing store that eventually exhausts memory. For cache use cases, almost every key should have an expiry or rely on an allkeys eviction policy.
Quick Check
What does the Redis command TTL mykey return if the key exists but has no expiration set?
Recap
You learned TTL and expiration in Redis:
- EXPIRE / SET ... EX set timeouts; TTL/PTTL inspect them; PERSIST removes them.
- Redis uses lazy plus active expiration.
- Eviction policies (volatile vs allkeys) handle memory pressure.
- Always set TTLs (or an allkeys policy) for cache keys.
Good expiration keeps a cache both fresh and bounded.
常见问题解答
「Redis 中的 TTL 与过期」课时是免费的吗?
是的 — 「Redis 中的 TTL 与过期」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Caching Strategies: Redis + CDN + Edge Computing 课程的其余内容,请升级到 CoddyKit PRO。 Caching Strategies: Redis + CDN + Edge Computing 课程共包含 4 节课。
「Redis 中的 TTL 与过期」这节课中我会学到什么?
了解 Redis 如何处理键过期:设置 TTL、使用 EXPIRE 和 SETEX 命令、懒惰过期与主动过期的工作方式,以及 maxmemory 驱逐策略如何与 TTL 交互。 你通过在浏览器中直接运行的动手代码来练习 Caching Strategies: Redis + CDN + Edge Computing,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Caching Strategies: Redis + CDN + Edge Computing 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Caching Strategies: Redis + CDN + Edge Computing 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「Redis 中的 TTL 与过期」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Caching Strategies: Redis + CDN + Edge Computing 课中编写并运行代码吗?
能。每节 Caching Strategies: Redis + CDN + Edge Computing 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Redis 缓存简介
- 用于缓存的 Redis 数据结构
- Redis 缓存基本操作
- Redis 中的 TTL 与过期