table of Contents
Reference article
to sum up
Reference article
Tell me about the 5 data structures of Redis and the corresponding usage scenarios in one breath, and the interview will need extra points
to sum up
data structure |
Features |
Application scenario |
Common commands |
String |
- Modifiable, dynamic string SDS (Simple Dynamic String)
- It can be a string, number (integer, floating point) or binary.
|
|
See article |
list |
- The amount of data is small, a contiguous memory,
ziplist(压缩列表) --- all elements are stored next to each other, and a contiguous memory is allocated;
- Large amount of data,
quicklist(快速链表) structure, that is ziplist+链表 , mixed structure
|
Since list is a list sorted in the order of insertion, there are relatively many application scenarios, such as:
- Message queue:
lpop and rpush (or vice versa, lpush and rpop ) can realize the function of queue
- Like list, comment list, ranking list of Moments:
lpush Commands and lrange commands can realize the function of the latest list. Each time lpush a new element is inserted into the list through the lrange command , and then the latest element list is read through the command.
|
|
hash |
(key,field,value) |
- Shopping cart: The
hset [key] [field] [value] command can be realized with 用户Id , 商品Id as field , the quantity of goods value , which happens to constitute the 3 elements of the shopping cart.
- Storage objects:
hash the type of (key, field, value) structure and objects (对象id, 属性, 值) of similar structure, may also be used to store objects.
|
|
set |
- Similar to HashSet, the internal key-value pairs are unordered and unique.
Disorder + unique |
- 好友、关注、粉丝、感兴趣的人集合:
1) sinter 命令可以获得A和B两个用户的共同好友; 2) sismember 命令可以判断A是否是B的好友; 3) scard 命令可以获取好友数量; 4) 关注时,smove 命令可以将B从A的粉丝集合转移到A的好友集合
- 首页展示随机:美团首页有很多推荐商家,但是并不能全部展示,set类型适合存放所有需要展示的内容,而
srandmember 命令则可以从中随机获取几个。
- 存储某活动中中奖的用户ID ,因为有去重功能,可以保证同一个用户不会中奖两次。
|
|
zset |
zset 也叫SortedSet 一方面它是个 set ,保证了内部 value 的唯一性;
- 另方面它可以给每个 value 赋予一个
score ,代表这个value的排序权重。
- 它的内部实现用的是一种叫作“
跳跃列表 ”的数据结构
唯一的值 + 相应的权重 |
zset 可以用做排行榜,但是和list 不同的是zset 它能够实现动态的排序,例如: 可以用来存储粉丝列表,value 值是粉丝的用户 ID,score 是关注时间,我们可以对粉丝列表按关注时间进行排序。
zset 还可以用来存储学生的成绩, value 值是学生的 ID, score 是他的考试成绩。 我们对成绩按分数进行排序就可以得到他的名次。
|
|