萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Redis Slowlog 功能詳解與 DEL 命令性能優化實戰

Slowlog 配置

CONFIG SET slowlog-log-slower-than 5000  -- 記錄超過 5000 微秒(5ms)的命令
CONFIG SET slowlog-max-len 25            -- 保留最近 25 條記錄

查看日志

SLOWLOG GET 10  -- 獲取最近 10 條慢查詢
SLOWLOG RESET   -- 清空日志

案例:DEL 命令阻塞問題

發現 DEL 大型集合(List/Set/ZSet)耗時 20ms+,阻塞單線程 Redis,影響並發與主從復制。

根因:DEL 對 String/Hash 為 O(1),對 List/Set/ZSet 為 O(N)。

解決方案:異步延遲刪除

1. Lua 腳本重命名並標記

local key = KEYS[1]
local type = redis.call('type', key).ok
if type == 'set' or type == 'zset' then
    local temp = 'gc:tmp:' .. redis.call('incr', 'gc:ids') .. ':' .. key
    redis.call('rename', key, temp)
    return redis.call('sadd', 'gc:' .. type, temp)
end
return redis.call('del', key)

2. 後台 Ruby 腳本分批清理

require 'redis'
r = Redis.new(driver: :hiredis)

# 清理 Set
r.srandmember('gc:set', 10000).each do |set|
    items = r.srandmember(set, 5000)
    if items.nil? || items.empty?
        r.srem('gc:set', set)
    else
        r.srem(set, items)
    end
end

# 清理 ZSet
r.srandmember('gc:zset', 10000).each do |zset|
    if r.zremrangebyrank(zset, 0, 5000) < 5000
        r.srem('gc:zset', zset)
    end
end

原理優勢

  • 將 O(N) 刪除拆分為多次小批量操作,避免長時間阻塞主線程。
  • 重命名後原 Key 立即不可見,業務邏輯不受影響。
  • 可根據數據量調整批次大小與執行頻率。

總結

Slowlog 是發現性能毛刺的利器。對大對象刪除採用「重命名+後台分批清理」模式,可有效規避 Redis 單線程阻塞風險,保障高並發場景下的服務穩定性。

copyright © 萬盛學電腦網 all rights reserved