副标题[/!--empirenews.page--]
我们天天都在使用 Redis 内置的命令行工具 redis-cli,久而久之以为它就是一个简单的交互式 Redis 数据结构手工操作程序,但是它背后强大的功能绝大多数同学可能闻所未闻。本节我们一起来挖掘这些鲜为人知的有趣用法。
执行单条命令
平时在访问 Redis 服务器,一般都会使用 redis-cli 进入交互模式,然后一问一答来读写服务器,这种情况下我们使用的是它的「交互模式」。还有另外一种「直接模式」,通过将命令参数直接传递给 redis-cli 来执行指令并获取输出结果。
- $ redis-cli incrby foo 5
- (integer) 5
- $ redis-cli incrby foo 5
- (integer) 10
如果输出的内容较大,还可以将输出重定向到外部文件
- $ redis-cli info > info.txt
- $ wc -l info.txt
- 120 info.txt
上面的命令指向的服务器是默认服务器地址,如果想指向特定的服务器可以这样
- // -n 2 表示使用第2个库,相当于 select 2
- $ redis-cli -h localhost -p 6379 -n 2 ping
- PONG
批量执行命令
在平时线上的开发过程中,有时候我们免不了要手工造数据,然后导入 Redis。通常我们会编写脚本程序来做这件事。不过还有另外一种比较便捷的方式,那就是直接使用 redis-cli 来批量执行一系列指令。
- $ cat cmds.txt
- set foo1 bar1
- set foo2 bar2
- set foo3 bar3
- ......
- $ cat cmds.txt | redis-cli
- OK
- OK
- OK
- ...
上面的指令使用了 Unix 管道将 cat 指令的标准输出连接到 redis-cli 的标准输入。其实还可以直接使用输入重定向来批量执行指令。
- $ redis-cli < cmds.txt
- OK
- OK
- OK
- ...
set 多行字符串
如果一个字符串有多行,你希望将它传入 set 指令,redis-cli 要如何做?可以使用 -x 选项,该选项会使用标准输入的内容作为最后一个参数。
- $ cat str.txt
- Ernest Hemingway once wrote,
- "The world is a fine place and worth fighting for."
- I agree with the second part.
- $ redis-cli -x set foo < str.txt
- OK
- $ redis-cli get foo
- "Ernest Hemingway once wrote,n"The world is a fine place and worth fighting for."nI agree with the second part.n"
重复执行指令
redis-cli 还支持重复执行指令多次,每条指令执行之间设置一个间隔时间,如此便可以观察某条指令的输出内容随时间变化。
- // 间隔1s,执行5次,观察qps的变化
- $ redis-cli -r 5 -i 1 info | grep ops
- instantaneous_ops_per_sec:43469
- instantaneous_ops_per_sec:47460
- instantaneous_ops_per_sec:47699
- instantaneous_ops_per_sec:46434
- instantaneous_ops_per_sec:47216
如果将次数设置为 -1 那就是重复无数次永远执行下去。如果不提供 -i 参数,那就没有间隔,连续重复执行。在交互模式下也可以重复执行指令,形式上比较怪异,在指令前面增加次数
- 127.0.0.1:6379> 5 ping
- PONG
- PONG
- PONG
- PONG
- PONG
- # 下面的指令很可怕,你的屏幕要愤怒了
- 127.0.0.1:6379> 10000 info
- .......
导出 csv
redis-cli 不能一次导出整个库的内容为 csv,但是可以导出单条指令的输出为 csv 格式。
- $ redis-cli rpush lfoo a b c d e f g
- (integer) 7
- $ redis-cli --csv lrange lfoo 0 -1
- "a","b","c","d","e","f","g"
- $ redis-cli hmset hfoo a 1 b 2 c 3 d 4
- OK
- $ redis-cli --csv hgetall hfoo
- "a","1","b","2","c","3","d","4"
(编辑:青岛站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|