Redis 命令行使用

发布时间: 更新时间: 总字数:1676 阅读时间:4m 作者: 分享 复制网址

Redis 命令行使用介绍

基础

登录命令:

redis-cli -h 127.0.0.1 -p 6379 -a <passport>

帮助:

[root@xiexianbin_cn ~]# redis-cli --help
redis-cli 3.2.8

Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
  -h <hostname>      Server hostname (default: 127.0.0.1).
  -p <port>          Server port (default: 6379).
  -s <socket>        Server socket (overrides hostname and port).
  -a <password>      Password to use when connecting to the server.
  -r <repeat>        Execute specified command N times.
  -i <interval>      When -r is used, waits <interval> seconds per command.
                     It is possible to specify sub-second times like -i 0.1.
  -n <db>            Database number.
  -x                 Read last argument from STDIN.
  -d <delimiter>     Multi-bulk delimiter in for raw formatting (default: \n).
  -c                 Enable cluster mode (follow -ASK and -MOVED redirections).
  --raw              Use raw formatting for replies (default when STDOUT is
                     not a tty).
  --no-raw           Force formatted output even when STDOUT is not a tty.
  --csv              Output in CSV format.
  --stat             Print rolling stats about server: mem, clients, ...
  --latency          Enter a special mode continuously sampling latency.
  --latency-history  Like --latency but tracking latency changes over time.
                     Default time interval is 15 sec. Change it using -i.
  --latency-dist     Shows latency as a spectrum, requires xterm 256 colors.
                     Default time interval is 1 sec. Change it using -i.
  --lru-test <keys>  Simulate a cache workload with an 80-20 distribution.
  --slave            Simulate a slave showing commands received from the master.
  --rdb <filename>   Transfer an RDB dump from remote server to local file.
  --pipe             Transfer raw Redis protocol from stdin to server.
  --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.
                     no reply is received within <n> seconds.
                     Default timeout: 30. Use 0 to wait forever.
  --bigkeys          Sample Redis keys looking for big keys.
  --scan             List all keys using the SCAN command.
  --pattern <pat>    Useful with --scan to specify a SCAN pattern.
  --intrinsic-latency <sec> Run a test to measure intrinsic system latency.
                     The test will run for the specified amount of seconds.
  --eval <file>      Send an EVAL command using the Lua script at <file>.
  --ldb              Used with --eval enable the Redis Lua debugger.
  --ldb-sync-mode    Like --ldb but uses the synchronous Lua debugger, in
                     this mode the server is blocked and script changes are
                     are not rolled back from the server memory.
  --help             Output this help and exit.
  --version          Output version and exit.

Examples:
  cat /etc/passwd | redis-cli -x set mypasswd
  redis-cli get mypasswd
  redis-cli -r 100 lpush mylist x
  redis-cli -r 100 -i 1 info | grep used_memory_human:
  redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3
  redis-cli --scan --pattern '*:12345*'

  (Note: when using --eval the comma separates KEYS[] from ARGV[] items)

When no command is given, redis-cli starts in interactive mode.
Type "help" in interactive mode for information on available commands
and settings.

登录

redis-cli -h 127.0.0.1 -p 6379 -a <passport>

检测是否启动

127.0.0.1:6379[1]> ping
PONG

查看 client 信息

127.0.0.1:6379[1]> CLIENT LIST

切换数据库

Redis 支持多个 DB,默认是16个(默认0-15,支持 redis.conf 中配置),你可以设置将数据存在哪一个 DB 中,不同 DB 间的数据具有隔离性,选择数据库:

redis 127.0.0.1:6379> SELECT 1
redis 127.0.0.1:6379[1]>

keys 相关操作

  • 查看 keys
keys *
keys *<key_name>
keys <key_name>
keys <key_name>*
  • keys 是否存在判断
exists <key_name>
  • 删除key
127.0.0.1:6379[1]> DEL <key_name>
(integer) 1

设置 TTL (数据过期设置)

Redis 支持按 key 设置过期时间,过期后值将被删除(在客户端看来是补删除了的)

用 TTL 命令可以获取某个 key 值的过期时间(-1表示永不过期)

redis 127.0.0.1:6379> SET name "John Doe"
OK
redis 127.0.0.1:6379> TTL name
(integer) -1

下面命令先用EXISTS命令查看key值是否存在,然后设置了5秒的过期时间

redis 127.0.0.1:6379> SET name "John Doe" #[NX|XX]
OK
redis 127.0.0.1:6379> EXISTS name
(integer) 1
redis 127.0.0.1:6379> EXPIRE name 5
(integer) 1

等同于
redis 127.0.0.1:6379> SET name "John Doe" EX 5

5秒后再查看

redis 127.0.0.1:6379> EXISTS name
(integer) 0
redis 127.0.0.1:6379> GET name
(nil)

这个值已经没有了。上在是直接设置多少秒后过期,你也可以设置在某个时间点过期,下面例子是设置2011-09-24 00:40:00过期。

redis 127.0.0.1:6379> SET name "John Doe"
OK
redis 127.0.0.1:6379> EXPIREAT name 1316805000
(integer) 1
redis 127.0.0.1:6379> EXISTS name
(integer) 0

清空当前数据库

127.0.0.1:6379[1]> FLUSHDB
OK
127.0.0.1:6379[1]> keys *
(empty list or set)

清空当所有据库

127.0.0.1:6379[1]> FLUSHALL

发布订阅

订阅:

redis 127.0.0.1:6379> SUBSCRIBE redisChat

Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3) (integer) 1

发布:

redis 127.0.0.1:6379> PUBLISH redisChat "Redis is a great caching technique"

(integer) 1

订阅结果:

1) "message"
2) "redisChat"
3) "Redis is a great caching technique"

数据类型

获取数据类型:

127.0.0.1:6379> TYPE <key_name>
hash

数据类型包括:

strings

127.0.0.1:6379> set foo bar
OK
127.0.0.1:6379> get foo
"bar"
> set name1 1
> incr name1 # 加1
> decr name1 # 减1
> incrby name1 10 # 加10
> decrby name 10 # # 减10

lists/queue

list 分左右:LPUSH、RPUSH

# 放入元素
LPUSH imlist 1
LPUSH imlist 2

# 查看所有元素,开始为 0,最后一个元素为 -1
lrange <key> [start] [end]
lrange imlist 0 -1

rpush imlist 3
lrange imlist 0 -1

# 获取元素数量
llen <key>

# 重左面/右面获取元素,返回 value
LPOP/RPOP

lpop <key>
rpop <key>

# 延时获取值,返回 `key, value`,若为空则阻塞,0 一直阻塞
blpop <key> 0
brpop <key> 0

组合为队列(先入先出):

  • LPUSH RPOP
  • RPUSH LPOP

说明:

  • 获取数据时,若无值直接返回 nil,会导致 CPU 等资源消耗过大,可以使用 brpop/blpop 添加一个阻塞时间

sets

127.0.0.1:6379> type _tooz_groups
set
127.0.0.1:6379> smembers _tooz_groups
1) "central-111111"
2) "ceilometer.notification"
3) "alarm_evaluator"
4) "central-global"

sadd <key-name> key1 key2 key3

smembers <key-name>

sadd <key-name> key4

# 判断是否存在
sismember <key-name> key5

# 移除元素
srem <key-name> key6

# 交集、并集、差集、补集,参考官方文档
SINTER s1 s2
SUNION s1 s2
SDIFF s1 s2

sorted sets/zsets

处理优先级任务:

  • 权重最小的 zrange names 0 0,使用后删除 zrem
  • 权重最小的 zrevrange names 0 0
zadd <key-name> <score> <name>
zadd names 1 n1
zadd names 2 n2
zadd names 3 n3

zrange names 0 -1
zrange names 0 -1 withscores
zrevrange names 0 -1
zrevrange names 0 -1 withscores

zrem <key-name> <name>

hashes

127.0.0.1:6379[1]> HSET myhash field1 "Hello"
(integer) 0
127.0.0.1:6379[1]> KEYS *
1) "myhash"
127.0.0.1:6379[1]> TYPE myhash
hash
127.0.0.1:6379[1]> HKEYS myhash
1) "field1"
127.0.0.1:6379[1]> HGETALL myhash
1) "field1"
2) "Hello"
127.0.0.1:6379[1]> HGET myhash field1
"Hello"

hash map

hmset <key-name> key1 val1 key2 val2
hgetall <key-name>

hmset <key-name> key1 val1-1 key2 val3-1

hset <key-name> key1 val1-1

hmget <key-name> key1 key2

hsetnx <key-name> key1 key2

hget <key-name> key1

hexists <key-name> key1

hdel <key-name> key1

del <key-name>

hash set

SETEX

设置key,并添加 ttl(seconds),SETEX 是一个原子性(atomic)操作,关联值和设置生存时间两个动作会在同一事务中完成,一般用作缓存

SETEX key seconds value

# 等价于
SET key value
EXPIRE key seconds  # 设置生存时间

SETNX

SETNX(SET if Not eXists) 如果不存在 key,则 SET,当 key 存在时,设置不成功

SETNX key value

最佳实践

分布式锁

SET <key> <value> NX PX <ttl>

说明:

  • NX 表示不存在 key 时才能设置成功
  • key 通过 ttl 控制时效
  • value 一般为随机值,由客户端生成

运维

关闭redis

使用 shutdown 命令,保证 Redis 在退出之前将数据保存在磁盘上

redis-cli shutdown

保存

执行保存后,一般在 /var/lib/redis/dump.rdb

redis-cli save

monitor

monitor 用来监视 redis 处理的每一个命令,使用 Ctrl-C 停止监听

redis-cli monitor
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数