Skip to content

Redis性能优化实战指南

引言

Redis作为高性能的内存数据库,在实际应用中如何优化其性能至关重要。本文将从多个角度详细介绍Redis性能优化的策略和实践。

内存优化

数据结构选择

  1. String vs Hash
redis
# 不推荐
SET user:1:name "张三"
SET user:1:age "25"
SET user:1:email "[email protected]"

# 推荐
HMSET user:1 name "张三" age "25" email "[email protected]"

内存配置

conf
maxmemory 2gb
maxmemory-policy allkeys-lru

持久化优化

RDB配置

conf
save 900 1
save 300 10
save 60 10000

AOF配置

conf
appendonly yes
appendfsync everysec

网络优化

Pipeline使用

python
import redis

r = redis.Redis(host='localhost', port=6379, db=0)
pipe = r.pipeline()

for i in range(1000):
    pipe.set(f'key:{i}', f'value:{i}')
pipe.execute()

批量操作

python
# 不推荐
for key in keys:
    redis.get(key)

# 推荐
redis.mget(*keys)

缓存策略

缓存更新策略

python
def get_user(user_id):
    # 先从缓存获取
    user = redis.get(f'user:{user_id}')
    if user:
        return user
        
    # 缓存未命中,从数据库获取
    user = db.get_user(user_id)
    
    # 设置缓存,加入过期时间
    redis.setex(f'user:{user_id}', 3600, user)
    return user

缓存穿透防护

python
def get_data(key):
    # 布隆过滤器检查
    if not bloom_filter.exists(key):
        return None
        
    # 获取数据
    data = cache.get(key)
    if data is None:
        data = db.get(key)
        if data:
            cache.set(key, data)
    return data

监控与告警

INFO命令监控

bash
redis-cli info | grep used_memory
redis-cli info | grep connected_clients
redis-cli info | grep rejected_connections

慢查询日志

conf
slowlog-log-slower-than 10000
slowlog-max-len 128

集群优化

分片策略

python
def get_redis_connection(key):
    # 一致性哈希
    node = consistent_hash.get_node(key)
    return redis_cluster[node]

主从配置

conf
# 主节点
bind 192.168.1.10
port 6379

# 从节点
slaveof 192.168.1.10 6379

键空间优化

键名规范

# 推荐的命名格式
object:id:field
user:1000:profile
order:9876:items

过期策略

python
# 设置合理的过期时间
redis.setex('session:token', 3600, 'session-data')
redis.expire('cache:data', 7200)

实战案例

限流实现

python
def is_action_allowed(user_id, action, period, max_count):
    key = f'hist:{user_id}:{action}'
    now = time.time() * 1000
    
    pipe = redis.pipeline()
    pipe.zadd(key, {now: now})
    pipe.zremrangebyscore(key, 0, now - period * 1000)
    pipe.zcard(key)
    pipe.expire(key, period + 1)
    _, _, count, _ = pipe.execute()
    
    return count <= max_count

总结

Redis性能优化是一个系统工程,需要从多个维度进行考虑和实践。通过合理的配置和使用方式,可以充分发挥Redis的性能优势。

参考资料

  1. Redis官方文档
  2. Redis设计与实现(黄健宏)
  3. Redis实战(Josiah L. Carlson)

幸运的人用童年治愈一生,不幸的人用一生治愈童年 —— 强爸