在我的Redis DB中,我有一些前缀:<numeric_id>哈希值。
有时我想把它们都原子地清除掉。如何在不使用分布式锁定机制的情况下做到这一点呢?
在我的Redis DB中,我有一些前缀:<numeric_id>哈希值。
有时我想把它们都原子地清除掉。如何在不使用分布式锁定机制的情况下做到这一点呢?
当前回答
如果你在键的名称中有空格,你可以在bash中使用:
redis-cli keys "pattern: *" | xargs -L1 -I '$' echo '"$"' | xargs redis-cli del
其他回答
@mcdizle的解决方案是行不通的,它只适用于一个条目。
这一项适用于具有相同前缀的所有键
EVAL "for i, name in ipairs(redis.call('KEYS', ARGV[1])) do redis.call('DEL', name); end" 0 prefix*
注意:你应该用你的密钥前缀替换'prefix'…
从redis 2.6.0开始,你可以运行lua脚本,它以原子方式执行。我从来没有写过,但我想应该是这样的
EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 prefix:[YOUR_PREFIX e.g delete_me_*]
警告:正如Redis文档所说,由于性能问题,关键字 命令不应用于生产中的常规操作,此 命令用于调试和特殊操作。读 更多的
请参阅EVAL文档。
如果你使用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
这是不用任何xargs魔法就能想到的最简单的方法
纯bash !
redis-cli DEL $(redis-cli KEYS *pattern*)
如果您的键包含特殊字符(例如Guide$CLASSMETADATA][1]),则其他答案可能无法工作。将每个键包装成引号将确保它们被正确删除:
redis-cli --scan --pattern sf_* | awk '{print $1}' | sed "s/^/'/;s/$/'/" | xargs redis-cli del