不用 KEYS 查找匹配模式的 key 并安全删除(SCAN + UNLINK)
Redis维护命令
# Cursor-based scan instead of KEYS (call again with the returned cursor until it returns 0):
SCAN 0 MATCH oturum:* COUNT 1000 TYPE string
# Number of keys matching the pattern:
redis-cli -h redis1 -p 6379 --scan --pattern 'oturum:*' --count 1000 | wc -l
# Bulk delete in batches of 500, freeing memory in the background:
redis-cli -h redis1 -p 6379 --scan --pattern 'oturum:*' --count 1000 | xargs -r -n 500 redis-cli -h redis1 -p 6379 UNLINK作用
在不阻塞服务器的情况下用游标扫描键空间,统计匹配模式和类型的 key,并用 UNLINK 批量删除,在后台释放内存。
适用场景
清理旧版本应用遗留的 key、查明某个前缀下有多少 key,或原本需要在生产中使用 KEYS 时。
注意
KEYS 一次性返回整个键空间,在大数据量下会阻塞服务器数秒;不要在生产中使用。对于扫描期间新增/删除的 key,SCAN 不提供完全保证,且可能多次返回同一个 key。包含空格或引号的 key 名在 xargs 中会出错。删除前检查数量和几个样本;无法撤销。