Redis

Redis是一个单线程 + Epoll + 计算向数据移动的内存型数据库。

常用命令

常见命令文档Redis命令参考手册完整版

redis-cli -h host -p port -a password

命令 描述
SELECT 切换数据库
Dbsize 查看当前数据库的key的数量
Flushdb 清空当前库
Flushall 通杀全部库
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
127.0.0.1:6379> help @generic

DEL key [key ...]
summary: Delete a key
since: 1.0.0

DUMP key
summary: Return a serialized version of the value stored at the specified key.
since: 2.6.0

EXISTS key [key ...]
summary: Determine if a key exists
since: 1.0.0

EXPIRE key seconds
summary: Set a key's time to live in seconds
since: 1.0.0

EXPIREAT key timestamp
summary: Set the expiration for a key as a UNIX timestamp
since: 1.2.0

KEYS pattern
summary: Find all keys matching the given pattern
since: 1.0.0

MIGRATE host port key| destination-db timeout [COPY] [REPLACE] [KEYS key]
summary: Atomically transfer a key from a Redis instance to another one.
since: 2.6.0

MOVE key db
summary: Move a key to another database
since: 1.0.0

OBJECT subcommand [arguments [arguments ...]]
summary: Inspect the internals of Redis objects
since: 2.2.3

PERSIST key
summary: Remove the expiration from a key
since: 2.2.0

PEXPIRE key milliseconds
summary: Set a key's time to live in milliseconds
since: 2.6.0

PEXPIREAT key milliseconds-timestamp
summary: Set the expiration for a key as a UNIX timestamp specified in milliseconds
since: 2.6.0

PTTL key
summary: Get the time to live for a key in milliseconds
since: 2.6.0

RANDOMKEY -
summary: Return a random key from the keyspace
since: 1.0.0

RENAME key newkey
summary: Rename a key
since: 1.0.0

RENAMENX key newkey
summary: Rename a key, only if the new key does not exist
since: 1.0.0

RESTORE key ttl serialized-value [REPLACE]
summary: Create a key using the provided serialized value, previously obtained using DUMP.
since: 2.6.0

SCAN cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate the keys space
since: 2.8.0

SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]
summary: Sort the elements in a list, set or sorted set
since: 1.0.0

TOUCH key [key ...]
summary: Alters the last access time of a key(s). Returns the number of existing keys specified.
since: 3.2.1

TTL key
summary: Get the time to live for a key
since: 1.0.0

TYPE key
summary: Determine the type stored at key
since: 1.0.0

UNLINK key [key ...]
summary: Delete a key asynchronously in another thread. Otherwise it is just as DEL, but non blocking.
since: 4.0.0

WAIT numreplicas timeout
summary: Wait for the synchronous replication of all the write commands sent in the context of the current connection
since: 3.0.0

POST ...options...
summary: Help not available
since: not known

SUBSTR key arg arg
summary: Help not available
since: not known

RESTORE-ASKING key arg arg ...options...
summary: Help not available
since: not known

HOST: ...options...
summary: Help not available
since: not known

PFDEBUG arg arg ...options...
summary: Help not available
since: not known

MODULE arg ...options...
summary: Help not available
since: not known

GEORADIUSBYMEMBER_RO key arg arg arg ...options...
summary: Help not available
since: not known

XSETID key arg
summary: Help not available
since: not known

GEORADIUS_RO key arg arg arg arg ...options...
summary: Help not available
since: not known

ASKING
summary: Help not available
since: not known

PSYNC arg arg
summary: Help not available
since: not known

REPLCONF ...options...
summary: Help not available
since: not known

LATENCY arg ...options...
summary: Help not available
since: not known

PFSELFTEST
summary: Help not available
since: not known

LOLWUT ...options...
summary: Help not available
since: not known

String

字符串有正向索引和反向索引,正向开头index=0开始,反向末尾index=-1开始。

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
127.0.0.1:6379> help @String

APPEND key value
summary: Append a value to a key
since: 2.0.0

DECR key
summary: Decrement the integer value of a key by one
since: 1.0.0

DECRBY key decrement
summary: Decrement the integer value of a key by the given number
since: 1.0.0

GET key
summary: Get the value of a key
since: 1.0.0

GETRANGE key start end
summary: Get a substring of the string stored at a key
since: 2.4.0

GETSET key value
summary: Set the string value of a key and return its old value
since: 1.0.0

INCR key
summary: Increment the integer value of a key by one
since: 1.0.0

INCRBY key increment
summary: Increment the integer value of a key by the given amount
since: 1.0.0

INCRBYFLOAT key increment
summary: Increment the float value of a key by the given amount
since: 2.6.0

MGET key [key ...]
summary: Get the values of all the given keys
since: 1.0.0

MSET key value [key value ...]
summary: Set multiple keys to multiple values
since: 1.0.1

MSETNX key value [key value ...]
summary: Set multiple keys to multiple values, only if none of the keys exist
since: 1.0.1

PSETEX key milliseconds value
summary: Set the value and expiration in milliseconds of a key
since: 2.6.0

SET key value [expiration EX seconds|PX milliseconds] [NX|XX]
summary: Set the string value of a key
since: 1.0.0

SETEX key seconds value
summary: Set the value and expiration of a key
since: 2.0.0

SETNX key value
summary: Set the value of a key, only if the key does not exist
since: 1.0.0

SETRANGE key offset value
summary: Overwrite part of a string at key starting at the specified offset
since: 2.2.0

STRLEN key
summary: Get the length of the value stored in a key
since: 2.2.0
1
2
3
Incr等数值命令适用场景:
抢购,秒杀,详情页,点赞,评论
规避并发下,对数据库的事务操作,完全由redis内存操作代替

BitMap

对二进制的Index位数进行设置值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
BITCOUNT key [start end]
summary: Count set bits in a string
since: 2.6.0

BITFIELD key [GET type offset] [SET type offset value] [INCRBY type offset increment] [OVERFLOW WRAP|SAT|FAIL]
summary: Perform arbitrary bitfield integer operations on strings
since: 3.2.0

BITOP operation destkey key [key ...]
summary: Perform bitwise operations between strings
since: 2.6.0

BITPOS key bit [start] [end]
summary: Find first bit set or clear in a string
since: 2.8.7

SETBIT key offset value
summary: Sets or clears the bit at offset in the string value stored at key
since: 2.2.0

GETBIT key offset
summary: Returns the bit value at offset in the string value stored at key
since: 2.2.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
案例:
setbit k1 1 1 0100 0000=@
setbit k1 7 1 0100 0001=A
setbit k1 9 1 0100 0001 0100 0000=A@

默认会转换成字符集 ascii 输出
其他一般叫做扩展字符集
扩展: 其他字符集不在对ascii重编码


redis的位操作适用场景:
1.有用户系统,统计用户登录天数,且窗口随机,每个用户有366位数据,一天一个,用BITCOUNT算出多少天
setbit sean 1 1
setbit sean 7 1
setbit sean 364 1
STRLEN sean
BITCOUNT sean -2 -1

2.活跃用户统计!随即窗口,多少用户多少个bit,一天一个key,数据与运算后使用BITCOUNT
setbit 20190101 1 1
setbit 20190102 1 1
setbit 20190102 7 1
bitop or destkey 20190101 20190102
BITCOUNT destkey 0 -1

Hash

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
127.0.0.1:6379> help @hash

HDEL key field [field ...]
summary: Delete one or more hash fields
since: 2.0.0

HEXISTS key field
summary: Determine if a hash field exists
since: 2.0.0

HGET key field
summary: Get the value of a hash field
since: 2.0.0

HGETALL key
summary: Get all the fields and values in a hash
since: 2.0.0

HINCRBY key field increment
summary: Increment the integer value of a hash field by the given number
since: 2.0.0

HINCRBYFLOAT key field increment
summary: Increment the float value of a hash field by the given amount
since: 2.6.0

HKEYS key
summary: Get all the fields in a hash
since: 2.0.0

HLEN key
summary: Get the number of fields in a hash
since: 2.0.0

HMGET key field [field ...]
summary: Get the values of all the given hash fields
since: 2.0.0

HMSET key field value [field value ...]
summary: Set multiple hash fields to multiple values
since: 2.0.0

HSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate hash fields and associated values
since: 2.8.0

HSET key field value
summary: Set the string value of a hash field
since: 2.0.0

HSETNX key field value
summary: Set the value of a hash field, only if the field does not exist
since: 2.0.0

HSTRLEN key field
summary: Get the length of the value of a hash field
since: 3.2.0

HVALS key
summary: Get all the values in a hash
since: 2.0.0

List

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
127.0.0.1:6379> help @list

BLPOP key [key ...] timeout
summary: Remove and get the first element in a list, or block until one is available
since: 2.0.0

BRPOP key [key ...] timeout
summary: Remove and get the last element in a list, or block until one is available
since: 2.0.0

BRPOPLPUSH source destination timeout
summary: Pop a value from a list, push it to another list and return it; or block until one is available
since: 2.2.0

LINDEX key index
summary: Get an element from a list by its index
since: 1.0.0

LINSERT key BEFORE|AFTER pivot value
summary: Insert an element before or after another element in a list
since: 2.2.0

LLEN key
summary: Get the length of a list
since: 1.0.0

LPOP key
summary: Remove and get the first element in a list
since: 1.0.0

LPUSH key value [value ...]
summary: Prepend one or multiple values to a list
since: 1.0.0

LPUSHX key value
summary: Prepend a value to a list, only if the list exists
since: 2.2.0

LRANGE key start stop
summary: Get a range of elements from a list
since: 1.0.0

LREM key count value
summary: Remove elements from a list
since: 1.0.0

LSET key index value
summary: Set the value of an element in a list by its index
since: 1.0.0

LTRIM key start stop
summary: Trim a list to the specified range
since: 1.0.0

RPOP key
summary: Remove and get the last element in a list
since: 1.0.0

RPOPLPUSH source destination
summary: Remove the last element in a list, prepend it to another list and return it
since: 1.2.0

RPUSH key value [value ...]
summary: Append one or multiple values to a list
since: 1.0.0

RPUSHX key value
summary: Append a value to a list, only if the list exists
since: 2.2.0

Set

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
127.0.0.1:6379> help @set

SADD key member [member ...]
summary: Add one or more members to a set
since: 1.0.0

SCARD key
summary: Get the number of members in a set
since: 1.0.0

SDIFF key [key ...]
summary: Subtract multiple sets
since: 1.0.0

SDIFFSTORE destination key [key ...]
summary: Subtract multiple sets and store the resulting set in a key
since: 1.0.0

SINTER key [key ...]
summary: Intersect multiple sets
since: 1.0.0

SINTERSTORE destination key [key ...]
summary: Intersect multiple sets and store the resulting set in a key
since: 1.0.0

SISMEMBER key member
summary: Determine if a given value is a member of a set
since: 1.0.0

SMEMBERS key
summary: Get all the members in a set
since: 1.0.0

SMOVE source destination member
summary: Move a member from one set to another
since: 1.0.0

SPOP key [count]
summary: Remove and return one or multiple random members from a set
since: 1.0.0

SRANDMEMBER key [count]
summary: Get one or multiple random members from a set
since: 1.0.0

SREM key member [member ...]
summary: Remove one or more members from a set
since: 1.0.0

SSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate Set elements
since: 2.8.0

SUNION key [key ...]
summary: Add multiple sets
since: 1.0.0

SUNIONSTORE destination key [key ...]
summary: Add multiple sets and store the resulting set in a key
since: 1.0.0
1
2
3
特性:
【无序】&&【随机性】&&【去重】
放入的多少不同,元素存储的顺序不同。

Sorted_set

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
127.0.0.1:6379> help @sorted_set

BZPOPMAX key [key ...] timeout
summary: Remove and return the member with the highest score from one or more sorted sets, or block until one is available
since: 5.0.0

BZPOPMIN key [key ...] timeout
summary: Remove and return the member with the lowest score from one or more sorted sets, or block until one is available
since: 5.0.0

ZADD key [NX|XX] [CH] [INCR] score member [score member ...]
summary: Add one or more members to a sorted set, or update its score if it already exists
since: 1.2.0

ZCARD key
summary: Get the number of members in a sorted set
since: 1.2.0

ZCOUNT key min max
summary: Count the members in a sorted set with scores within the given values
since: 2.0.0

ZINCRBY key increment member
summary: Increment the score of a member in a sorted set
since: 1.2.0

ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX]
summary: Intersect multiple sorted sets and store the resulting sorted set in a new key
since: 2.0.0

ZLEXCOUNT key min max
summary: Count the number of members in a sorted set between a given lexicographical range
since: 2.8.9

ZPOPMAX key [count]
summary: Remove and return members with the highest scores in a sorted set
since: 5.0.0

ZPOPMIN key [count]
summary: Remove and return members with the lowest scores in a sorted set
since: 5.0.0

ZRANGE key start stop [WITHSCORES]
summary: Return a range of members in a sorted set, by index
since: 1.2.0

ZRANGEBYLEX key min max [LIMIT offset count]
summary: Return a range of members in a sorted set, by lexicographical range
since: 2.8.9

ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
summary: Return a range of members in a sorted set, by score
since: 1.0.5

ZRANK key member
summary: Determine the index of a member in a sorted set
since: 2.0.0

ZREM key member [member ...]
summary: Remove one or more members from a sorted set
since: 1.2.0

ZREMRANGEBYLEX key min max
summary: Remove all members in a sorted set between the given lexicographical range
since: 2.8.9

ZREMRANGEBYRANK key start stop
summary: Remove all members in a sorted set within the given indexes
since: 2.0.0

ZREMRANGEBYSCORE key min max
summary: Remove all members in a sorted set within the given scores
since: 1.2.0

ZREVRANGE key start stop [WITHSCORES]
summary: Return a range of members in a sorted set, by index, with scores ordered from high to low
since: 1.2.0

ZREVRANGEBYLEX key max min [LIMIT offset count]
summary: Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings.
since: 2.8.9

ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
summary: Return a range of members in a sorted set, by score, with scores ordered from high to low
since: 2.2.0

ZREVRANK key member
summary: Determine the index of a member in a sorted set, with scores ordered from high to low
since: 2.0.0

ZSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate sorted sets elements and associated scores
since: 2.8.0

ZSCORE key member
summary: Get the score associated with the given member in a sorted set
since: 1.2.0

ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight] [AGGREGATE SUM|MIN|MAX]
summary: Add multiple sorted sets and store the resulting sorted set in a new key
since: 2.0.0

Bloom

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
BF.ADD key ...options...
summary: Help not available
since: not known

BF.EXISTS key ...options...
summary: Help not available
since: not known

BF.INSERT key ...options...
summary: Help not available
since: not known

BF.DEBUG key ...options...
summary: Help not available
since: not known

BF.MEXISTS key ...options...
summary: Help not available
since: not known

BF.INFO key ...options...
summary: Help not available
since: not known

BF.MADD key ...options...
summary: Help not available
since: not known
1
redis-server --loadmodule  /opt/redis/redisbloom.so

redis

持久化

RDB

redis

1
2
3
4
#主动触发阻塞的RDB操作(如关机,明确调用)
127.0.0.1:6379> save
#主动触发异步的RDB操作(Fork进程)
127.0.0.1:6379> bgsage

AOF

redis

1
2
#主动触发重写AOP操作
127.0.0.1:6379> BGREWRITEAOF

常见问题

Redis如何保证Sorted_set的排序和插入效率?

底层使用跳表Skip List实现的,详细链接


Redis如何淘汰过期的keys?

Redis keys过期有两种方式:被动和主动方式。

当一些客户端尝试访问它时,key会被发现并主动的过期。

当然,这样是不够的,因为有些过期的keys,永远不会访问他们。 无论如何,这些keys应该过期,所以定时随机测试设置keys的过期时间。所有这些过期的keys将会从密钥空间删除。

具体就是Redis每秒10次做的事情:

  1. 测试随机的20个keys进行相关过期检测。
  2. 删除所有已经过期的keys。
  3. 如果有多于25%的keys过期,重复步奏1.

这是一个平凡的概率算法,基本上的假设是,我们的样本是这个密钥控件,并且我们不断重复过期检测,直到过期的keys的百分百低于25%,这意味着,在任何给定的时刻,最多会清除1/4的过期keys。


Redis如何解决缓存穿透?

布隆过滤器,采用多种映射函数将一个元素映射到bitmap的多个位中,当判断元素是否存在时,需要这些位的都是1,若有一个不为1,则不存在。

概率解决问题

1
2
3
4
1.穿透了,不存在
2.client,增加redis中的key,value标记
3.数据库增加了元素
4.完成元素对bloom的添加

Redis的hash和JDK的hash的区别

参考资料:

redis的渐进式rehash:其重新计算hash和数据搬运的过程是发生在增删改查的操作中的,而不是集中一次性完成的。

字典rehash底层实现与Java区别

总结:

1
2
3
1.Redis的Hash结构是 【数组 + 链表】,Redis的扩容和收缩,是利用两个哈希表来完成。
2.Redis字典创建时就有两个哈希表,不扩容的情况下,只使用ht[0]这个哈希表,当发生扩容和收缩时,才会用到ht[1]哈希表
3.Redis使用MurmurHash2算法来计算键的哈希值,扩容时会伴随重新计算Hash值的行为。
1
2
3
4
5
//Redis字典结构
typedef struct dict{
dictht ht[2];//哈希表,分为h[0],h[1]哈希表,通常情况下使用h[0],h[1]用于rehash
itn trehashidx;//rehash索引,扩容时使用,当rehash完成时,值为-1
}
1
2
1.JDK1.8的Hash结构是 【数组 + 链表 + 红黑树】,HashMap只支持扩容,不支持收缩。
2.HashMap扩容阶段不会产生重新计算Hash值的行为。
功能 Java Redis
扩容 集中式扩容 渐进式扩容
收缩 不支持收缩 支持收缩
Hash冲突 采用链表和红黑树解决冲突 采用链表解决冲突
Hash值变化 不变 变化

Java为什么不支持收缩?
Java是以空间换时间,支持收缩不符合它的理念。

最后更新: 2021年02月26日 21:49

原始链接: https://midkuro.gitee.io/2020/05/27/redis-command/

× 请我吃糖~
打赏二维码