当前位置:网站首页>Meituan two sides: redis five basic data structures?
Meituan two sides: redis five basic data structures?
2022-07-22 14:15:00 【Xi. Technical chopping】
Redis 5 Basic data structures (String、List、Hash、Set、Sorted Set) Often asked in an interview , Let's review this article .
Here is the body .
You can Redis Found on the official website Redis The data structure is introduced in great detail :
Redis Data Structures[1]
Redis Data types tutorial[2]
The future as Redis The release of the new version , New data structures may appear , By looking up Redis Introduction to the official website , You can always get the most reliable information .
String( character string )
Introduce
String yes Redis The simplest and most commonly used data structure in .
String Is a binary secure data structure , It can be used to store any type of data, such as strings 、 Integers 、 Floating point numbers 、 picture ( The image base64 Encoding or decoding or the path of the picture )、 Serialized object .
although Redis Yes, it is C Written language , however Redis Not used C String representation of , It's about building a kind of Simple dynamic string (Simple Dynamic String,SDS). Compared with C The native string of ,Redis Of SDS You can save not only text data, but also binary data , And the complexity of getting the length of the string is O(1)(C String is O(N)), besides ,Redis Of SDS API Is safe , No buffer overflow .
Common commands
command | Introduce |
---|---|
SET key value | Set the specified key Value |
SETNX key value | Only in key Set when not present key Value |
GET key | Get specified key Value |
MSET key1 value1 key2 value2 … | Set one or more specified key Value |
MGET key1 key2 ... | Get one or more specified key Value |
STRLEN key | return key The length of the stored string value |
INCR key | take key The value of the number stored in is increased by one |
DECR key | take key Subtract one from the number stored in |
EXISTS key | Determine the specified key Whether there is |
DEL key( Universal ) | Delete specified key |
EXPIRE key seconds( Universal ) | To assign to key Set expiration time |
more Redis String Commands and detailed instructions , Please check out Redis Introduction to the official website :https://redis.io/commands/?group=string .
Basic operation :
> SET key value
OK
> GET key
"value"
> EXISTS key
(integer) 1
> STRLEN key
(integer) 5
> DEL key
(integer) 1
> GET key
(nil)
Batch settings :
> MSET key1 value1 key2 value2
OK
> MGET key1 key2 # Get more than one in batch key Corresponding value
1) "value1"
2) "value2"
Counter ( When the content of the string is an integer, you can use ):
> SET number 1
OK
> INCR number # take key The value of the number stored in is increased by one
(integer) 2
> GET number
"2"
> DECR number # take key Subtract one from the number stored in
(integer) 1
> GET number
"1"
Set expiration time ( The default is never expire ):
> EXPIRE key 60
(integer) 1
> SETNX key 60 value # Set the value and set the expiration time
OK
> TTL key
(integer) 56
Application scenarios
Scenarios that need to store regular data
give an example : cache session、token、 Picture address 、 Serialized object ( Compared with Hash Storage saves more memory ).
Relevant command :
SET
、GET
.
Scenes that need to be counted
give an example : Number of requests per user unit time ( Simple current limiting can be used )、 Number of page visits per unit time .
Relevant command :
SET
、GET
、INCR
、DECR
.
Distributed lock
utilize SETNX key value
Command can realize the simplest distributed lock ( There are some drawbacks , It is generally not recommended to implement distributed locks in this way ).
List( list )
Introduce
Redis Medium List In fact, it is the implementation of linked list data structure . I am here Linear data structure : Array 、 Linked list 、 Stack 、 queue [3] This article introduces the data structure of linked list in detail , I won't introduce more here .
Many high-level programming languages have built-in implementation of linked lists, such as Java Medium LinkedList
, however C The language doesn't implement the linked list , therefore Redis It realizes its own linked list data structure .Redis Of List The implementation of is a Double linked list , That is, it can support reverse lookup and traversal , Easier to operate , But it brings some extra memory overhead .
Common commands
command | Introduce |
---|---|
RPUSH key value1 value2 ... | At the end of the specified list ( On the right ) Add one or more elements |
LPUSH key value1 value2 ... | At the head of the specified list ( On the left ) Add one or more elements |
LSET key index value | The list index will be specified index The value of the position is set to value |
LPOP key | Remove and get the first element of the specified list ( Leftmost ) |
RPOP key | Remove and get the last element of the specified list ( Far right ) |
LLEN key | Get the number of list elements |
LRANGE key start end | To obtain a list of start and end Between The elements of |
more Redis List Commands and detailed instructions , Please check out Redis Introduction to the official website :https://redis.io/commands/?group=list .
adopt RPUSH/LPOP
perhaps LPUSH/RPOP
Implementation queue :
> RPUSH myList value1
(integer) 1
> RPUSH myList value2 value3
(integer) 3
> LPOP myList
"value1"
> LRANGE myList 0 1
1) "value2"
2) "value3"
> LRANGE myList 0 -1
1) "value2"
2) "value3"
adopt RPUSH/RPOP
perhaps LPUSH/LPOP
Implementation stack :
> RPUSH myList2 value1 value2 value3
(integer) 3
> RPOP myList2 # take list The head of ( Far right ) Take out the elements
"value3"
I drew a special picture for everyone to understand RPUSH
, LPOP
, lpush
, RPOP
command :
adopt LRANGE
View the list elements corresponding to the subscript range :
> RPUSH myList value1 value2 value3
(integer) 3
> LRANGE myList 0 1
1) "value1"
2) "value2"
> LRANGE myList 0 -1
1) "value1"
2) "value2"
3) "value3"
adopt LRANGE
command , You can be based on List Realize paging query , Very high performance !
adopt LLEN
Check the list length :
> LLEN myList
(integer) 3
Application scenarios
Information flow display
give an example : The latest article 、 What's new .
Relevant command :
LPUSH
、LRANGE
.
Message queue
Redis List Data structures can be used as message queues , It's just that the function is too simple and has many defects , This is not recommended .
relatively speaking ,Redis 5.0 A new data structure is added Stream
It is more suitable for message queuing , But the function is still very simple . Compared with professional message queuing , There are still many deficiencies, such as the problem of message loss and accumulation .
Hash( Hash )
Introduce
Redis Medium Hash It's a String Type of field-value( Key value pair ) Mapping table , Ideal for storing objects , When following up , You can directly modify the values of some fields in this object .
Hash Be similar to JDK1.8 Before HashMap
, The internal implementation is similar ( Array + Linked list ). however ,Redis Of Hash More optimizations .
Common commands
command | Introduce |
---|---|
HSET key field value | Set the value of the specified field in the specified hash table |
HSETNX key field value | Only when the specified field does not exist, set the value of the specified field |
HMSET key field1 value1 field2 value2 ... | At the same time, one or more field-value ( Domain - value ) Set to the specified hash table |
HGET key field | Get the value of the specified field in the specified hash table |
HMGET key field1 field2 ... | Get the value of one or more specified fields in the specified hash table |
HGETALL key | Get all key value pairs in the specified hash table |
HEXISTS key field | Check whether the specified field in the specified hash table exists |
HDEL key field1 field2 ... | Delete one or more hash table fields |
HLEN key | Get the number of fields in the specified hash table |
more Redis Hash Commands and detailed instructions , Please check out Redis Introduction to the official website :https://redis.io/commands/?group=hash .
Analog object data storage :
> HMSET userInfoKey name "guide" description "dev" age "24"
OK
> HEXISTS userInfoKey name # see key Corresponding value Whether the field specified in the .
(integer) 1
> HGET userInfoKey name # Gets the value of the specified field stored in the hash table .
"guide"
> HGET userInfoKey age
"24"
> HGETALL userInfoKey # Gets the specified in the hash table key All fields and values of
1) "name"
2) "guide"
3) "description"
4) "dev"
5) "age"
6) "24"
> HSET userInfoKey name "GuideGeGe"
> HGET userInfoKey name
"GuideGeGe"
Application scenarios
Object data storage scenario
give an example : User information 、 Commodity information 、 The article information 、 Shopping cart information .
Relevant command :
HSET
( Set the value of a single field )、HMSET
( Set values for multiple fields )、HGET
( Get the value of a single field )、HMGET
( Get the value of multiple fields ).
Set( aggregate )
Introduce
Redis Medium Set A type is an unordered set , The elements in the set have no order, but they are all unique , It's kind of like Java Medium HashSet
. When you need to store a list of data , You don't want duplicate data ,Set Is a good choice , also Set It provides a way to judge whether an element is in a Set Important interfaces within a collection , This is also List What cannot be provided .
You can be based on Set Easy intersection 、 Combine 、 Operation of difference set , For example, you can store all the followers of a user in a collection , Put all its fans in a collection . In this case ,Set Can be very convenient to achieve such as common concern 、 Common fans 、 Common preferences and other functions . This process is also the process of intersection .
Common commands
command | Introduce |
---|---|
SADD key member1 member2 ... | Add one or more elements to the specified collection |
SMEMBERS key | Get all the elements in the specified collection |
SCARD key | Get the number of elements in the specified set |
SISMEMBER key member | Determine whether the specified element is in the specified set |
SINTER key1 key2 ... | Get the intersection of all given sets |
SINTERSTORE destination key1 key2 ... | Store the intersection of all given sets in destination in |
SUNION key1 key2 ... | Get the union of all given sets |
SUNIONSTORE destination key1 key2 ... | Store the union of all given sets in destination in |
SDIFF key1 key2 ... | Get the difference set of all given sets |
SDIFFSTORE destination key1 key2 ... | Store the difference set of all given sets in destination in |
SPOP key count | Randomly remove and get one or more elements in the specified set |
SRANDMEMBER key count | Randomly obtain a specified number of elements in a specified set |
more Redis Set Commands and detailed instructions , Please check out Redis Introduction to the official website :https://redis.io/commands/?group=set .
Basic operation :
> SADD mySet value1 value2
(integer) 2
> SADD mySet value1 # Duplicate elements are not allowed , So add failed
(integer) 0
> SMEMBERS mySet
1) "value1"
2) "value2"
> SCARD mySet
(integer) 2
> SISMEMBER mySet value1
(integer) 1
> SADD mySet2 value2 value3
(integer) 2
mySet
:value1
、value2
.mySet2
:value2
、value3
.
Find the intersection :
> SINTERSTORE mySet3 mySet mySet2
(integer) 1
> SMEMBERS mySet3
1) "value2"
Union :
> SUNION mySet mySet2
1) "value3"
2) "value2"
3) "value1"
Difference set :
> SDIFF mySet mySet2 # The difference set is composed of all that belong to mySet But that does not belong to A A collection of elements of
1) "value1"
Application scenarios
Scenarios where the data to be stored cannot be duplicated
give an example : Website UV Statistics ( The scenario with a huge amount of data is still
HyperLogLog
More suitable for )、 I like the article 、 Dynamic likes and other scenes .Relevant command :
SCARD
( Get the number of sets ) .
You need to get the intersection of multiple data sources 、 Union and difference scenes
give an example : Common friends ( intersection )、 Common fans ( intersection )、 Pay close attention to ( intersection )、 Friend recommendation ( Difference set )、 Music to recommend ( Difference set ) 、 Subscription number recommendation ( Difference set + intersection ) Such as the scene .
Relevant command :
SINTER
( intersection )、SINTERSTORE
( intersection )、SUNION
( Combine )、SUNIONSTORE
( Combine )、SDIFF
( intersection )、SDIFFSTORE
( intersection ).
Scenarios that require random access to elements in the data source
give an example : The lottery system 、 Random .
Relevant command :
SPOP
( Randomly get the elements in the set and remove , It is suitable for scenes where repeated winning is not allowed )、SRANDMEMBER
( Get the elements in the collection at random , Suitable for scenarios that allow repeated winning ).
Sorted Set( Ordered set )
Introduce
Sorted Set Be similar to Set, But and Set comparison ,Sorted Set Added a weight parameter score
, To enable elements in a collection to press score
Arrange in order , You can also use score
To get a list of elements . It's kind of like Java in HashMap
and TreeSet
The combination of .
Common commands
command | Introduce |
---|---|
ZADD key score1 member1 score2 member2 ... | Add one or more elements to the specified ordered set |
ZCARD KEY | Gets the number of elements in the specified ordered set |
ZSCORE key member | Gets the name of the specified element in the specified ordered collection score value |
ZINTERSTORE destination numkeys key1 key2 ... | Store the intersection of all given ordered sets in destination in , Corresponding to the same element score Value for SUM Aggregation operation ,numkeys Is the number of sets |
ZUNIONSTORE destination numkeys key1 key2 ... | Union , And the other ZINTERSTORE similar |
ZDIFF destination numkeys key1 key2 ... | Difference set , And the other ZINTERSTORE similar |
ZRANGE key start end | Get the specified ordered set start and end Between the elements (score From low to high ) |
ZREVRANGE key start end | Get the specified ordered set start and end Between the elements (score From high to the bottom ) |
ZREVRANK key member | Gets the rank of the specified element in the specified ordered collection (score Sort from large to small ) |
more Redis Sorted Set Commands and detailed instructions , Please check out Redis Introduction to the official website :https://redis.io/commands/?group=sorted-set .
Basic operation :
> ZADD myZset 2.0 value1 1.0 value2
(integer) 2
> ZCARD myZset
2
> ZSCORE myZset value1
2.0
> ZRANGE myZset 0 1
1) "value2"
2) "value1"
> ZREVRANGE myZset 0 1
1) "value1"
2) "value2"
> ZADD myZset2 4.0 value2 3.0 value3
(integer) 2
myZset
:value1
(2.0)、value2
(1.0) .myZset2
:value2
(4.0)、value3
(3.0) .
Get the rank of the specified element :
> ZREVRANK myZset value1
0
> ZREVRANK myZset value2
1
Find the intersection :
> ZINTERSTORE myZset3 2 myZset myZset2
1
> ZRANGE myZset3 0 1 WITHSCORES
value2
5
Union :
> ZUNIONSTORE myZset4 2 myZset myZset2
3
> ZRANGE myZset4 0 2 WITHSCORES
value1
2
value3
3
value2
5
Difference set :
> ZDIFF 2 myZset myZset2 WITHSCORES
value1
2
Application scenarios
It is necessary to randomly obtain the elements in the data source and sort them according to a certain weight
give an example : Various leaderboards, such as the leaderboard for gifts in the live studio 、 Wechat ranking of friends 、 Ranking list of the ranks in the glory of the king 、 Topic heat ranking list and so on .
Relevant command :
ZRANGE
( Sort from small to large ) 、ZREVRANGE
( Sort from large to small )、ZREVRANK
( Specify the element ranking ).
Scenarios where the data to be stored has priority or importance For example, priority task queue .
give an example : Priority task queue .
Relevant command :
ZRANGE
( Sort from small to large ) 、ZREVRANGE
( Sort from large to small )、ZREVRANK
( Specify the element ranking ).
If this article helps you , Don't forget to give me a 3 even , give the thumbs-up , forward , Comment on ,
Learn more JAVA Knowledge and skills , Pay attention to Blogger learning JAVA Courseware , Source code , Installation package , There are also the latest interview materials of big factories, etc
I'll see you next time .
Collection It's like whoring for nothing , Praise is the truth .
边栏推荐
- RenderFlex children have non-zero flex but incoming height constraints are unbounded.
- 51 MCU peripherals: Keys
- Kubernetes scheduling concept and workflow
- Seven schemes of Web real-time message push
- 实习打怪之路:JS中检测数据类型的方法
- dom——事件链(捕获目标和捕获)
- 微信打开时支持消息通知横幅引热议;Google和甲骨文的云服务因英国高温天气而下线;谷歌发布开源开发语言Carbon|极客头条
- 异常检测 and 自编码器(2)
- NVIDIA可编程推理加速器TensorRT学习笔记(一)——开始
- Advanced C language: data storage (floating point)
猜你喜欢
Redis数据结构分析(一)
Which Hong Kong cloud server or physical server is more prone to downtime?
[take you to the cloud native system] Part 4: kubernetes from entry to mastery
Microservice architecture | service registration and Discovery Center / configuration center / message bus - [nacos] TBC
Ardunio開發——水泵操作過程
MMD PMX import unit related data
飞行员兄弟
Redis data structure analysis (I)
Pytorch (IV) -- pytorch model definition
3.zabbix安装
随机推荐
Implementing DDD based on ABP -- domain service, application service and dto practice
【机器学习】机器学习中到底需不需要进行样本平衡
Http实战之缓存、重定向
51单片机外设篇:按键
2.zabbix概念
Under file operation (C language)
kube-scheduler的调度上下文
7种 实现web实时消息推送的方案
Is it safe for Huatai Securities to open an account? Can the handling charge be in case?
Redis data structure analysis (I)
Load and display the label information of raincityspaces
微服务架构 | 服务注册发现中心/配置中心/消息总线 - [nacos] TBC...
Which pits of BigDecimal precision
From 20s to 500ms, I used these three methods
常用功能的测试用例
Kubernetes scheduling concept and workflow
dom——事件代理
c语言分层理解(c语言分支和循环语句)
The 22 pictures show you in-depth analysis of prefix, infix, suffix expressions and expression evaluation
9. ZABBIX SNMP monitoring