在我的Redis DB中,我有一些前缀:<numeric_id>哈希值。

有时我想把它们都原子地清除掉。如何在不使用分布式锁定机制的情况下做到这一点呢?


当前回答

这个对我有用,但可能不是原子:

redis-cli keys "stats.*" | cut -d ' ' -f2 | xargs -d '\n' redis-cli DEL

其他回答

@itamar的回答很棒,但对回复的解析对我来说并不管用,特别是在给定扫描中没有找到键的情况下。一个可能更简单的解决方案,直接从控制台:

redis-cli -h HOST -p PORT  --scan --pattern "prefix:*" | xargs -n 100 redis-cli DEL

这也使用了SCAN,它在生产中比KEYS更可取,但不是原子的。

/ /所有

你认为这是没有意义的命令,但有时Redis命令像DEL不能正确工作,来拯救这个

redis-cli KEYS "*" | xargs -i redis-cli EXPIRE {} 1 it's life hack

可怜人的大规模删除?

也许你可以把它们都设置为同一秒到期——比如未来的几分钟——然后等到那个时候,看到它们都在同一时间“自毁”。

但我不确定那有多原子。

我尝试了上面提到的大部分方法,但对我来说都不奏效,经过一些搜索,我发现了以下几点:

如果你在redis上有多个数据库,你应该使用-n [number]来确定数据库。 如果你有几个键使用del,但如果有成千上万或数百万个键,最好使用unlink,因为unlink是非阻塞的,而del是阻塞的,更多信息请访问这个页面unlink vs del 键也像del和is blocking

所以我用这段代码按模式删除键:

 redis-cli -n 2 --scan --pattern '[your pattern]' | xargs redis-cli -n 2 unlink 

如果你使用windows环境,请遵循以下步骤,它一定会工作:

Download GOW from here - https://github.com/bmatzelle/gow/wiki (because xargs command doesn't works in windows) Download redis-cli for Windows (detailed explanation is here - https://medium.com/@binary10111010/redis-cli-installation-on-windows-684fb6b6ac6b) Run cmd and open directory where redis-cli stores (example: D:\Redis\Redis-x64-3.2.100) if you want to delete all keys which start with "Global:ProviderInfo" execute this query (it's require to change bold parameters (host, port, password, key) and write yours, because of this is only example): redis-cli -h redis.test.com -p 6379 -a redispassword --raw keys "Global:ProviderInfo*" | xargs redis-cli -h redis.test.com -p 6379 -a redispassword del