0%

Redis特殊命令

原子性是关系型数据库事务的四大特性之一,指的是一个事务中的所有操作,要么全部完成,要么全部不完成,不会结束在中间某个环节。对于Redis而言,命令的原子性指的是一个操作的不可以再分,操作要么执行,要么不执行。

一、eval

  1. Redis的单个命令是能保证原子性的,因为本身是单线程。然而在有些场景下往往需要同时执行多个命令来保证业务,多个命令的时候Redis就无法保证原子性了。此时一般的解决方案大概有几种,要么看能否合并多个命令变为一个,要么通过事务实现,要么就通过lua脚本实现,当然还有别的实现方案,此处就不做深入讨论。对于Redis,Eval命令就是使用Lua解释器执行脚本。

  2. 语法eval script numkeys key [key ...] arg [arg ...]

    • script:参数是一段 Lua 5.1 脚本程序。脚本不必(也不应该)定义为一个 Lua 函数。
    • numkeys:用于指定键名参数的个数。
    • key [key …]:从EVAL命令后的第三个参数开始算起,表示在脚本中所用到的那些Redis键(key),这些键名参数可以在Lua中通过全局变量KEYS数组获取,用1为基址的形式访问(KEYS[1],KEYS[2]以此类推)。
    • arg [arg …]:附加参数,在Lua中通过全局变量ARGV数组访问,访问的形式和KEYS变量类似。
  3. 使用

    • 全部参数:eval "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 key2 arg1 arg2
    • 部分参数:eval "for i=1,512 do redis.call('RPUSH',KEYS[1],i)end" 1 list_key
    • 部分参数:eval "for i=1,513 do redis.call('HSET',KEYS[1],i,i+1)end" 1 my_hash
  4. 参考

二、memory

  1. Redis4.0版本加入了memory命令,查看key的内存占用方便了好多。

  2. 查看memory命令的用法

    • usage:查看某个key内存占用情况
    • stats:查看整体内存占用情况
    • doctor:内存的使用状态
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    127.0.0.1:6379> memory help
    1) MEMORY <subcommand> [<arg> [value] [opt] ...]. Subcommands are:
    2) DOCTOR
    3) Return memory problems reports.
    4) MALLOC-STATS Return internal statistics report from the memory allocator.
    5) PURGE
    6) Attempt to purge dirty pages for reclamation by the allocator.
    7) STATS
    8) Return information about the memory usage of the server.
    9) USAGE <key> [SAMPLES <count>]
    10) Return memory in bytes used by <key> and its value. Nested values are
    11) sampled up to <count> times (default: 5).
    12) HELP
    13) Prints this help.
  3. 使用

    • memory stats
      • peak.allocated:allocator分配的内存峰值
      • total.allocated:allocator分配当前内存字节数
      • startup.allocated:redis启动完成使用的内存字节数
      • replication.backlog:redis复制积压缓冲区内存使用字节数
        • 通过repl-backlog-size参数设置
      • clients.slaves:master侧所有slave clients消耗的内存字节数,非常重要
      • clients.normal:所有客户端消耗内存节字数,非常重要
        • client list可查看当前连接的客户端
      • aof.buffer:aof buffer使用内存字节数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
127.0.0.1:6379> memory stats
1) "peak.allocated"
2) (integer) 103653824
3) "total.allocated"
4) (integer) 103100176
5) "startup.allocated"
6) (integer) 1062608
7) "replication.backlog"
8) (integer) 0
9) "clients.slaves"
10) (integer) 0
11) "clients.normal"
12) (integer) 87296
13) "aof.buffer"
14) (integer) 0
15) "lua.caches"
16) (integer) 0
17) "db.0"
18) 1) "overhead.hashtable.main"
2) (integer) 131928
3) "overhead.hashtable.expires"
4) (integer) 89168
19) "overhead.total"
20) (integer) 1371000
21) "keys.count"
22) (integer) 2479
23) "keys.bytes-per-key"
24) (integer) 41160
25) "dataset.bytes"
26) (integer) 101729176
27) "dataset.percentage"
28) "99.697769165039062"
29) "peak.percentage"
30) "99.465873718261719"
31) "allocator.allocated"
32) (integer) 103063264
33) "allocator.active"
34) (integer) 10148864
35) "allocator.resident"
36) (integer) 10148864
37) "allocator-fragmentation.ratio"
38) "0.098472177982330322"
39) "allocator-fragmentation.bytes"
40) (integer) -92914400
41) "allocator-rss.ratio"
42) "1"
43) "allocator-rss.bytes"
44) (integer) 0
45) "rss-overhead.ratio"
46) "1.0037332773208618"
47) "rss-overhead.bytes"
48) (integer) 37888
49) "fragmentation"
50) "0.098839797079563141"
51) "fragmentation.bytes"
52) (integer) -92876512
  • memory doctor

    1
    2
    3
    4
    5
    6
    7
    8
    9
    127.0.0.1:6379> memory doctor
    #无问题
    Hi Sam, I can't find any memory issue in your instance. I can only account for what occurs on this base.

    #有问题
    Sam, I detected a few issues in this Redis instance memory implants:
    * Peak memory: In the past this instance used more than 150% the memory that is currently using. The allocator is normally not able to release memory after a peak, so you can expect to see a big fragmentation ratio, however this is actually harmless and is only due to the memory peak, and if the Redis instance Resident Set Size (RSS) is currently bigger than expected, the memory will be used as soon as you fill the Redis instance with more data. If the memory peak was only occasional and you want to try to reclaim memory, please try the MEMORY PURGE command, otherwise the only other option is to shutdown and restart the instance.

    I'm here to keep you safe, Sam. I want to help you.
  • memory usage

    1
    2
    127.0.0.1:6379> memory usage key_name samples 100
    (integer) 21064
  1. 参考

三、info

  1. info
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# Server
redis_version:6.2.5
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:915e5480613bc9b6
redis_mode:standalone
os:Darwin 19.6.0 x86_64
arch_bits:64
multiplexing_api:kqueue
atomicvar_api:c11-builtin
gcc_version:4.2.1
process_id:493
process_supervised:no
run_id:330e788f0fbf47bc6b8897377297ba395735716a
tcp_port:6379
server_time_usec:1637043981269469
uptime_in_seconds:359640
uptime_in_days:4
hz:10
configured_hz:10
lru_clock:9654029
executable:/usr/local/opt/redis/bin/redis-server
config_file:/usr/local/etc/redis.conf
io_threads_active:0

# Clients
connected_clients:1
cluster_connections:0
maxclients:10000
client_recent_max_input_buffer:32
client_recent_max_output_buffer:0
blocked_clients:0
tracking_clients:0
clients_in_timeout_table:0

# Memory
used_memory:1149792
used_memory_human:1.10M
used_memory_rss:1220608
used_memory_rss_human:1.16M
used_memory_peak:1211088
used_memory_peak_human:1.15M
used_memory_peak_perc:94.94%
used_memory_overhead:1080536
used_memory_startup:1062608
used_memory_dataset:69256
used_memory_dataset_perc:79.44%
allocator_allocated:1102672
allocator_active:1182720
allocator_resident:1182720
total_system_memory:8589934592
total_system_memory_human:8.00G
used_memory_lua:37888
used_memory_lua_human:37.00K
used_memory_scripts:0
used_memory_scripts_human:0B
number_of_cached_scripts:0
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
allocator_frag_ratio:1.07
allocator_frag_bytes:80048
allocator_rss_ratio:1.00
allocator_rss_bytes:0
rss_overhead_ratio:1.03
rss_overhead_bytes:37888
mem_fragmentation_ratio:1.11
mem_fragmentation_bytes:117936
mem_not_counted_for_evict:0
mem_replication_backlog:0
mem_clients_slaves:0
mem_clients_normal:17440
mem_aof_buffer:0
mem_allocator:libc
active_defrag_running:0
lazyfree_pending_objects:0
lazyfreed_objects:0

# Persistence
loading:0
current_cow_size:0
current_cow_size_age:0
current_fork_perc:0.00
current_save_keys_processed:0
current_save_keys_total:0
rdb_changes_since_last_save:1
rdb_bgsave_in_progress:0
rdb_last_save_time:1636707639
rdb_last_bgsave_status:err
rdb_last_bgsave_time_sec:0
rdb_current_bgsave_time_sec:-1
rdb_last_cow_size:0
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_last_cow_size:0
module_fork_in_progress:0
module_fork_last_cow_size:0

# Stats
total_connections_received:7
total_commands_processed:3537
instantaneous_ops_per_sec:0
total_net_input_bytes:366934
total_net_output_bytes:1871237
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.00
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:3
expired_stale_perc:0.00
expired_time_cap_reached_count:0
expire_cycle_cpu_milliseconds:2434
evicted_keys:0
keyspace_hits:2682
keyspace_misses:774
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:440
total_forks:2558
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
tracking_total_keys:0
tracking_total_items:0
tracking_total_prefixes:0
unexpected_error_replies:0
total_error_replies:60
dump_payload_sanitizations:0
total_reads_processed:3605
total_writes_processed:3594
io_threaded_reads_processed:0
io_threaded_writes_processed:0

# Replication
role:master
connected_slaves:0
master_failover_state:no-failover
master_replid:4d884c932517b011cd3185b4254e45a865342e0a
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

# CPU
used_cpu_sys:215.527509
used_cpu_user:54.147090
used_cpu_sys_children:0.289700
used_cpu_user_children:0.001551

# Modules

# Errorstats
errorstat_ERR:count=4
errorstat_MISCONF:count=56

# Cluster
cluster_enabled:0

# Keyspace
db0:keys=7,expires=2,avg_ttl=1120235800

四、client

  1. 用于返回所有连接到服务器的客户端信息和统计数据。
  2. 使用client help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
1) CLIENT <subcommand> [<arg> [value] [opt] ...]. Subcommands are:
2) CACHING (YES|NO)
3) Enable/disable tracking of the keys for next command in OPTIN/OPTOUT modes.
4) GETREDIR
5) Return the client ID we are redirecting to when tracking is enabled.
6) GETNAME
7) Return the name of the current connection.
8) ID
9) Return the ID of the current connection.
10) INFO
11) Return information about the current client connection.
12) KILL <ip:port>
13) Kill connection made from <ip:port>.
14) KILL <option> <value> [<option> <value> [...]]
15) Kill connections. Options are:
16) * ADDR (<ip:port>|<unixsocket>:0)
17) Kill connections made from the specified address
18) * LADDR (<ip:port>|<unixsocket>:0)
19) Kill connections made to specified local address
20) * TYPE (normal|master|replica|pubsub)
21) Kill connections by type.
22) * USER <username>
23) Kill connections authenticated by <username>.
24) * SKIPME (YES|NO)
25) Skip killing current connection (default: yes).
26) LIST [options ...]
27) Return information about client connections. Options:
28) * TYPE (NORMAL|MASTER|REPLICA|PUBSUB)
29) Return clients of specified type.
30) UNPAUSE
31) Stop the current client pause, resuming traffic.
32) PAUSE <timeout> [WRITE|ALL]
33) Suspend all, or just write, clients for <timout> milliseconds.
34) REPLY (ON|OFF|SKIP)
35) Control the replies sent to the current connection.
36) SETNAME <name>
37) Assign the name <name> to the current connection.
38) UNBLOCK <clientid> [TIMEOUT|ERROR]
39) Unblock the specified blocked client.
40) TRACKING (ON|OFF) [REDIRECT <id>] [BCAST] [PREFIX <prefix> [...]]
41) [OPTIN] [OPTOUT]
42) Control server assisted client side caching.
43) TRACKINGINFO
44) Report tracking status for the current connection.
45) HELP
46) Prints this help.

五、config

六、slowlog

  1. slowlog help
1
2
3
4
5
6
7
8
9
10
11
12
 1) SLOWLOG <subcommand> [<arg> [value] [opt] ...]. Subcommands are:
2) GET [<count>]
3) Return top <count> entries from the slowlog (default: 10). Entries are
4) made of:
5) id, timestamp, time in microseconds, arguments array, client IP and port,
6) client name
7) LEN
8) Return the length of the slowlog.
9) RESET
10) Reset the slowlog.
11) HELP
12) Prints this help.

七、monitor

八、type

九、object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 1) OBJECT <subcommand> [<arg> [value] [opt] ...]. Subcommands are:
2) ENCODING <key>
3) Return the kind of internal representation used in order to store the value
4) associated with a <key>.
5) FREQ <key>
6) Return the access frequency index of the <key>. The returned integer is
7) proportional to the logarithm of the recent access frequency of the key.
8) IDLETIME <key>
9) Return the idle time of the <key>, that is the approximated number of
10) seconds elapsed since the last access to the key.
11) REFCOUNT <key>
12) Return the number of references of the value associated with the specified
13) <key>.
14) HELP
15) Prints this help.