Redis 常用命令

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

redis是一个基于内存的,key/value数据库,常用来做缓存。

介绍

Redis 的优点

  • 性能极高:Redis 能支持超过 100K+ 每秒的读写频率。
  • 丰富的数据类型
  • 原子:Redis的所有操作都是原子性的,同时Redis还支持对几个操作全并后的原子性执行。
  • 丰富的特性:Redis还支持 publish/subscribe、通知、key 过期等等特性。
  • 支持分布式部署
  • 支持 rdp、aof 持久化存储

Redis 数据类型

常用数据类型如下:

  • strings
  • lists ([]interface{})
  • sets (集合,元素不重复)
  • sorted sets
  • hashes(hash map)
  • bitmap

-key

  • 命名规则:[a-zA-Z][a-zA-Z0-9_]*
  • 层级:使用 : 分隔,如 “app:version”

安装部署

集群模式 Cluster mode

无。

主从模式 Master slave mode

无。

云托管模式设置 Replicated mode

哨兵模式 Sentinel mode

  • 安装 RPM
yum install redis
  • 配置 redis.conf

redis master /etc/redis.conf 配置:

bind 0.0.0.0
daemonize yes
masterauth <master-password>
requirepass <password>
systemctl start redis.service

redis slave /etc/redis.conf 配置:

与 master 相同,新增:

slaveof <redis-master-ip> <redis-port>
systemctl start redis.service
  • 配置 redis-sentinel.conf

redis /etc/redis-sentinel.conf 配置:

bind 0.0.0.0
protected-mode no
port 26379
sentinel monitor mymaster <redis-master-ip> <redis-port> 2
sentinel auth-pass mymaster <password>

启动服务

systemctl start redis.service
systemctl start redis-sentinel.service
systemctl enable redis.service
systemctl enable redis-sentinel.service

单Redis节点模式 Single instance mode

yum install redis -y

修改配置 vim /etc/redis.conf

bind 0.0.0.0
requirepass <passport>
daemonize yes

启动

systemctl enable redis
systemctl start redis

redis-cli

登录命令:

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.

常用命令

集群模式 Cluster mode

无。

主从模式 Master slave mode

无。

云托管模式设置 Replicated mode

127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:2
slave0:ip=127.0.0.1,port=6380,state=online,offset=547,lag=0
slave1:ip=127.0.0.1,port=6381,state=online,offset=547,lag=1
master_repl_offset:547
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:2
repl_backlog_histlen:546

哨兵模式 Sentinel mode

参考:https://redis.io/topics/sentinel

  • 集群信息
127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:2
slave0:ip=127.0.0.1,port=6380,state=online,offset=547,lag=0
slave1:ip=127.0.0.1,port=6381,state=online,offset=547,lag=1
master_repl_offset:547
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:2
repl_backlog_histlen:546
  • 查看所有信息
[root@xiexianbin_cn ~]# redis-cli -h 127.0.0.1 -p 26379
127.0.0.1:26379> info
# Server
redis_version:4.0.6
redis_git_sha1:2334ceab
redis_git_dirty:0
redis_build_id:5b333971ded73847
redis_mode:sentinel
os:Linux 3.10.0-514.26.2.el7.x86_64 x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:6.4.0
process_id:12
run_id:57b456d0d88c51b45e73b5f4787f93797215567b
tcp_port:26379
uptime_in_seconds:12512
uptime_in_days:0
hz:17
lru_clock:6772127
executable:/redis-sentinel
config_file:/sentinel.conf

# Clients
connected_clients:4
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0

# CPU
used_cpu_sys:75.26
used_cpu_user:26.09
used_cpu_sys_children:0.00
used_cpu_user_children:0.00

# Stats
total_connections_received:6
total_commands_processed:54321
instantaneous_ops_per_sec:3
total_net_input_bytes:3096315
total_net_output_bytes:347993
instantaneous_input_kbps:0.20
instantaneous_output_kbps:0.02
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
migrate_cached_sockets:0
slave_expires_tracked_keys:0
active_defrag_hits:0
active_defrag_misses:0
active_defrag_key_hits:0
active_defrag_key_misses:0

# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=mymaster,status=ok,address=172.22.134.190:6379,slaves=2,sentinels=4
  • 查看 Sentinel 信息
127.0.0.1:26379> info sentinel
# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=mymaster,status=ok,address=172.22.134.190:6379,slaves=2,sentinels=4
  • 扩展列出其他信息
info Server
info Clients
info CPU
info Stats
info Sentinel
  • 列出主Redis服务实例
127.0.0.1:26379> sentinel masters
1)  1) "name"
    2) "mymaster"
    3) "ip"
    4) "172.22.134.190"
    5) "port"
    6) "6379"
...
   37) "failover-timeout"
   38) "180000"
   39) "parallel-syncs"
   40) "1"
  • 列出所有从实例
127.0.0.1:26379> sentinel slaves mymaster
1)  1) "name"
    2) "127.0.0.1:6379"
    3) "ip"
    4) "127.0.0.1"
    5) "port"
...
   39) "slave-repl-offset"
   40) "3431244"
2)  1) "name"
    2) "172.22.227.237:6379"
    3) "ip"
    4) "172.22.227.237"
    5) "port"
    6) "6379"
...
   37) "slave-priority"
   38) "100"
   39) "slave-repl-offset"
   40) "3431244"
  • 列出主实例的 IP 地址和端口号
127.0.0.1:26379> sentinel get-master-addr-by-name mymaster
1) "172.22.134.190"
2) "6379"
  • 重置所有名字和给定模式 pattern 相匹配的主服务器
127.0.0.1:26379> sentinel reset mymaster
(integer) 1
  • 主动的failover
127.0.0.1:26379> sentinel failover mymaster
OK

单Redis节点模式 Single instance mode

无。

常用命令

登录

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个,你可以设置将数据存在哪一个 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

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>

https://redis.io/commands/hset

示例

访问链接

redis://[:password]@localhost:6379/1

ceilometer 实践

127.0.0.1:6379> SMEMBERS _tooz_groups
1) "central-111"
2) "ceilometer.notification"
3) "alarm_evaluator"
4) "central-global"
127.0.0.1:6379> type _tooz_group:central-111
hash
127.0.0.1:6379> type _tooz_group:ceilometer.notification
hash
127.0.0.1:6379> type _tooz_group:central-global
hash
127.0.0.1:6379> type _tooz_group:alarm_evaluator
hash
127.0.0.1:6379> HGETALL _tooz_group:central-111
1) "__created__"
2) "1"
127.0.0.1:6379> HGETALL _tooz_group:ceilometer.notification
 1) "__created__"
 2) "1"
 3) "32cd6ee7-ab1b-4004-bbf6-224ac93bb2f2"
 4) "\xc4\x00"
 ...
127.0.0.1:6379> HGETALL _tooz_group:central-global
1) "__created__"
2) "1"
127.0.0.1:6379> HGETALL _tooz_group:alarm_evaluator
1) "__created__"
2) "1"
3) "382a6e79-1841-466d-8001-49d603267f07"
4) "\xc4\x00"
 ...
127.0.0.1:6379>

windows client

https://redisdesktop.com/download

参考

https://redis.readthedocs.io http://www.runoob.com/redis

reids 配置方法:

k8s 部署 redis 集群:

最新评论
加载中...
Home Archives Categories Tags Statistics