1. 安装
1.1. 普通安装
docker run -d \
--name simon-redis-server \
-p 6379:6379 \
redis:7.2-alpine \
redis-server --appendonly yesredis:7.2-alpine:轻量镜像(推荐)--appendonly yes:开启持久化(可选)
1.2. 密码安装
基于 Alpine 的镜像),你可以直接通过环境变量 REDIS_PASSWORD 来设置密码。
docker run -d \
--name simon-redis-server \
-p 6380:6379 \
redis:7.2-alpine \
redis-server --requirepass "BWOYO0R7oDt40y0shH6t" --appendonly yes1.3. 密码可持久化
docker run -itd --name simon-redis \
-p 56379:6379 \
-v $PWD/redis/data:/data \
redis:7.2-alpine \
redis-server --requirepass "BWOYO0R7oDt40y0shH6t" --appendonly yes
docker run -d \
--name redis-custom \
-p 6381:6379 \
-v $PWD/redis.conf:/usr/local/etc/redis/redis.conf \
redis:7.2-alpine \
redis-server /usr/local/etc/redis/redis.confRedis 是一个高性能的键值存储系统,支持多种数据结构(如字符串、哈希、列表、集合、有序集合等),并提供了丰富的 API。以下是对 Redis 主要 API 的整理,并附带实际使用案例(基于 Redis 命令行或 Redis 客户端如 redis-cli)。
1.4. python
import redis
r = redis.Redis(
host='localhost',
port=6379,
db=0,
decode_responses=True
)
print(r.ping()) # → True
r.set("test", "hello from python without password")
print(r.get("test"))1.5. python-密码
import redis
r = redis.Redis(
host='localhost',
port=6380, # 注意端口!
password='MySecretPassword123!',
db=0,
decode_responses=True
)
print(r.ping()) # → True
r.set("test", "hello from python with password")
print(r.get("test"))1.6. python 连接池
import redis
pool = redis.ConnectionPool(
host='localhost',
port=6380,
password='MySecretPassword123!',
db=0,
decode_responses=True,
max_connections=20
)
r = redis.Redis(connection_pool=pool)
print(r.get("test"))1.7. go
package main
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
var ctx = context.Background()
func main() {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // 无密码留空
DB: 0,
})
pong, err := rdb.Ping(ctx).Result()
if err != nil {
panic(err)
}
fmt.Println("Ping:", pong) // → PING
err = rdb.Set(ctx, "test", "hello from go without password", 0).Err()
if err != nil {
panic(err)
}
val, err := rdb.Get(ctx, "test").Result()
if err != nil {
panic(err)
}
fmt.Println("Value:", val)
}1.8. go 含密码
package main
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
var ctx = context.Background()
func main() {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6380", // 注意端口!
Password: "MySecretPassword123!",
DB: 0,
})
pong, err := rdb.Ping(ctx).Result()
if err != nil {
panic(err)
}
fmt.Println("Ping:", pong)
err = rdb.Set(ctx, "test", "hello from go with password", 0).Err()
if err != nil {
panic(err)
}
val, err := rdb.Get(ctx, "test").Result()
if err != nil {
panic(err)
}
fmt.Println("Value:", val)
}1.9. go 连接池
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6380",
Password: "MySecretPassword123!",
DB: 0,
PoolSize: 20,
MinIdleConns: 5,
})1.10. 选择数据库
# 默认是0号数据库
SELECT 12. 通用命令(Key 相关)
2.1. 案例:设置用户会话过期
SET session:abc "user_data_here"
EXPIRE session:abc 3600 # 1小时后自动删除
TTL session:abc # 查看剩余时间3. 字符串(String)
最基础的数据类型,可存文本、数字等。
3.1. 案例:计数器与缓存
SET article:1:title "Redis入门指南"
SETEX article:1:views 86400 "125" # 缓存24小时阅读数
INCR article:1:daily_views # 每次访问+1
GET article:1:daily_views # 获取当前访问数4. 哈希(Hash)
适合存储对象,字段-值对结构。
4.1. 案例:存储用户信息
HSET user:1001 name "Alice" email "alice@example.com" score 95
HGET user:1001 name # → "Alice"
HGETALL user:1001 # → 所有字段和值
HINCRBY user:1001 score 5 # 分数+55. 列表(List)
有序可重复元素,支持从两端操作。
✅ 案例:消息队列 / 最新动态
RPUSH news "新闻A"
RPUSH news "新闻B"
RPUSH news "新闻C"
LRANGE news 0 2 # 获取前三条
LPOP news # 处理一条(FIFO)6. 集合(Set)
无序不重复元素集合,支持交并差运算。
6.1. 案例:标签系统 / 好友共同兴趣
SADD user:1:tags "music" "sports" "coding"
SADD user:2:tags "sports" "travel" "coding"
SINTER user:1:tags user:2:tags # → "sports", "coding" (共同兴趣)7. 有序集合(Sorted Set / ZSet)
每个成员关联一个分数(score),按分数排序。
7.1. 案例:排行榜系统
ZADD game:leaderboard 850 "player1"
ZADD game:leaderboard 920 "player2"
ZADD game:leaderboard 760 "player3"
ZREVRANGE game:leaderboard 0 2 WITHSCORES # 前三名及分数
ZRANK game:leaderboard "player1" # 查看排名(从0开始)8. 其他实用命令
8.1. 发布订阅(Pub/Sub)
# 订阅频道
SUBSCRIBE chatroom
# 发布消息
PUBLISH chatroom "Hello everyone!"8.2. 事务(Transactions)
MULTI
SET name "Tom"
INCR counter
EXEC8.3. Lua 脚本(原子操作)
EVAL "return redis.call('GET', KEYS[1])" 1 mykey9. 综合案例:电商购物车 + 排行榜 + 库存
# 用户1001添加商品到购物车(Hash)
HSET cart:1001 item_001 2 item_002 1
# 商品销量排行榜(ZSet)
ZINCRBY sales_rank 1 "item_001" # 销量+1
ZREVRANGE sales_rank 0 9 WITHSCORES
# 商品库存(String + INCR/DECR)
SET stock:item_001 100
DECR stock:item_001 # 下单减库存
GET stock:item_001 # 剩余库存
# 设置订单过期(30分钟未支付自动取消)
SETEX order:ORD20240501 1800 "pending"10. 参考文档:
官方命令文档:https://redis.io/commands/
中文手册:http://redisdoc.com/