查看 Redis 某种类型的所有 key
Redis 没有提供按类型查找 key 的方法。 我们自己通过管道组合命令来查询。
注意,这仅适合 key 不太多的情况,如果太多,可能会很卡。
方法
redis-cli -a [Password] KEYS "*" 2>/dev/null | xargs -t -I {} redis-cli -a [Password] TYPE "{}" 2>&1 | grep -x -B 2 [type] | grep -v Warning
[type]
替换成你要查找的类型- 当 Redis 存在密码时,使用
-a [Password]
。这将导致 Redis 警告:Warning: Using a password with ‘-a’ or ‘-u’ option on the command line interface may not be safe.。所以 grep -B 2 打印结果前两行才能看到 key 名称。 grep -v Warning
排除 Redis 警告信息。
如果你的 grep 支持 -P 选项,那么你有一种更加完美的解决方式:
如果你的系统是 MacOS 且不支持 -P,可参考以下 《附录 - MacOS 安装 GUN grep》
redis-cli -a [Password] KEYS "*" 2>/dev/null | xargs -t -I {} redis-cli -a [Password] TYPE &