Skip to content

Redis 基础

Use Redis as in-memory 键-值存储: 字符串, 列表, hashes, 设置, and TTL.

你将学到

  • 什么 Redis 是 and 为什么它 是所以快
  • 字符串, 列表, hashes, 设置, and 排序设置数据类型
  • 设置 expiration 使用 TTL and EXPIRE
  • 常见 use 情况: 缓存, 会话, 速率 limiting
  • Persistence and trade-off 的 in-memory storage

概念讲解

什么是 Redis?

Redis (Remote Dictionary Server) is an in-memory key-value data store. Because all data lives in RAM, reads and writes are extremely fast — typically sub-millisecond. Redis is commonly used for caching, session storage, real-time analytics, message queues, and leaderboards. It is not a replacement for your primary database; it sits alongside it to accelerate hot data.

数据类型

Redis is more than a simple key-value store — it supports rich data structures:

  • Strings — the simplest type; a key holds a string, number, or binary blob
  • Lists — ordered collections, push/pop from either end; good for queues
  • Hashes — maps of field-value pairs; like a mini object per key
  • Sets — unordered collections of unique strings; good for tags, unique visitors
  • Sorted Sets — sets with an associated score; perfect for leaderboards and rankings

Each data type has its own set of commands, and Redis executes them atomically.

TTL and Expiration

Every key can have a time-to-live (TTL) — after the TTL expires, the key is automatically deleted. This is essential for caching (cache entries expire and get refreshed) and sessions (sessions expire after inactivity). Set TTL with EXPIRE 键 seconds or at creation time with SET 键 值 EX seconds.

Common Use Cases

  • Caching — store the result of an expensive database query; serve from Redis on subsequent requests
  • Session storage — web session data with automatic expiration
  • Rate limiting — count requests per user per minute using INCR with TTL
  • Leaderboards — sorted sets with scores for real-time rankings
  • Pub/Sub — real-time message broadcasting

Persistence

Although Redis is in-memory, it can persist data to disk: RDB (point-in-time snapshots) and AOF (append-only log of every write). This protects against data loss on restart, but persistence is asynchronous by default — a crash can lose the last few seconds of writes. Redis is designed for speed first, durability second.

示例代码

              -- Set a string with expiration (cache a value for 1 hour)
SET cache:user:42:profile '{"name":"Ada","role":"admin"}' EX 3600

-- Get the value
GET cache:user:42:profile

-- Work with a hash (object-like data)
HSET user:42 name "Ada Lovelace" email "[email protected]" role "admin"
HGET user:42 name
HGETALL user:42

-- Sorted set for a leaderboard
ZADD leaderboard 1500 "player_a" 2300 "player_b" 1800 "player_c"
ZREVRANGE leaderboard 0 2 WITHSCORES  -- top 3 players

-- Rate limiting: 100 requests per minute
INCR rate:api:user:42
EXPIRE rate:api:user:42 60  -- reset every 60 seconds
            

Five Redis 模式: 缓存字符串使用 TTL, hash for 对象数据, 排序设置 for leaderboard, and INCR 使用 TTL for 速率 limiting.

动手试一试

常见错误

错误写法

存储大 datasets in Redis 不使用 monitoring memory

正确做法

Redis 存储一切 in RAM. 设置 maxmemory policy (e.g. allkeys-lru) and monitor usage. Eviction policies prevent out-的-memory crashes.

错误写法

Using Redis as 仅数据存储不使用 persistence

正确做法

启用 AOF or RDB persistence 如果数据必须 survive restarts. For 关键数据, keep 主要复制 in durable 数据库 and use Redis as 缓存.

练习 Redis 基础

2 个练习

练习 Redis 基础

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误