第八章:最佳实践¶
键命名规范¶
键命名规范:
- 使用冒号分隔:user:1001:profile
- 包含业务前缀:order:20240101:12345
- 避免过长:控制在 100 字符以内
- 使用统一前缀:app:module:key
内存优化¶
数据结构选择¶
# 使用 Hash 存储对象
HSET user:1001 name "Alice" age 25 email "alice@example.com"
# 使用压缩列表
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
# 使用位图
SETBIT online:20240101 1001 1
GETBIT online:20240101 1001
内存淘汰策略¶
# 内存限制
maxmemory 4gb
# 淘汰策略
maxmemory-policy allkeys-lru # LRU 淘汰所有键
# maxmemory-policy volatile-lru # LRU 淘汰过期键
# maxmemory-policy allkeys-random # 随机淘汰
性能优化¶
Pipeline¶
import redis
r = redis.Redis()
# 使用 Pipeline 批量操作
pipe = r.pipeline()
for i in range(1000):
pipe.set(f"key:{i}", i)
pipe.execute()
Lua 脚本¶
-- 原子操作:扣减库存
local stock = redis.call('GET', KEYS[1])
if tonumber(stock) >= tonumber(ARGV[1]) then
redis.call('DECRBY', KEYS[1], ARGV[1])
return 1
else
return 0
end
# 执行 Lua 脚本
script = """
local stock = redis.call('GET', KEYS[1])
if tonumber(stock) >= tonumber(ARGV[1]) then
redis.call('DECRBY', KEYS[1], ARGV[1])
return 1
else
return 0
end
"""
result = r.eval(script, 1, 'stock:product1', 10)
监控¶
关键指标¶
小结¶
最佳实践要点:
- 键命名:规范命名
- 内存优化:数据结构选择、淘汰策略
- 性能优化:Pipeline、Lua 脚本
- 监控:内存、统计、慢查询
完成本教程后,你应该能够高效使用 Redis。