Home  >  Article  >  Database  >  In-depth analysis of the data structure in Redis and talk about application scenarios

In-depth analysis of the data structure in Redis and talk about application scenarios

青灯夜游
青灯夜游forward
2022-01-18 09:51:451965browse

This article will give you an in-depth understanding of the data structures in Redis and see the application scenarios of these data structures. I hope it will be helpful to you!

In-depth analysis of the data structure in Redis and talk about application scenarios

Redis data types and application scenarios

Redis is a Key-Value storage system written in ANSI C language. The type of key is string. [Related recommendations: Redis video tutorial]

8 data types of value data types:

  • Common data types

    • string string type

    • list list type

    • set collection type

    • sortedset(zset) ordered set type

    • hash type

  • ##Uncommon data type

    • bitmap bitmap type

    • geo location type

    • stream type

  • Note

    Commands in Redis ignore case, (set SET), keys do not ignore case (NAME name)

In-depth analysis of the data structure in Redis and talk about application scenarios

string string type

Redis’ String can express three types of values: string, integer, floating point number 100.01 is a six-digit string

Common commands

Command nameCommand formatCommand descriptionsetset key valueAssignmentgetget keyGet the valuegetsetgetset key valueGet the value and assign the valuemsetMSET key1 value1 key2 value2 .. keyN valueNSet the values ​​of multiple mgetMGET KEY1 KEY2 .. KEYNReturn the values ​​​​of all (one or more) given keysEXPIREEXPIRE key secondsSet the expiration time (seconds) of a keyappend append key valueAppend value to the endstrlenstrlen keyGet the string lengthsetnxsetnx key valueAssignment is used when value does not existincrincr keyIncrement numberincrbyincrby key incrementIncrease the specified integerdecrdecr keyDecrease the numberdecrbydecrby key decrementDecrease the specified integer

Application scenarios

  • 1. Object cache

  • 2. Single value cache

  • 3. incr is used for optimistic locking incr: incremental number, which can be used to implement optimistic locking watch (transaction)

  • 4. setnx is used for distributed locking when the value is not Use assignment when it exists and can be used to implement distributed locks

  • 5, counters

  • 6, and Web cluster session sharing

Examples of common methods

dockerRedis:0>keys *
dockerRedis:0>append testName 2
"1"
dockerRedis:0>exists testName
"1"
dockerRedis:0>append testName " 1234"
"6"
dockerRedis:0>get testName
"2 1234"
dockerRedis:0>set testName1 "testName1"
"OK"
dockerRedis:0>get testName1
"testName1"
dockerRedis:0>getset testName2 "testName2"
null
dockerRedis:0>get testName2
"testName2"
dockerRedis:0>strlen testName
"6"
dockerRedis:0>set incrTest "10"
"OK"
dockerRedis:0>incr incrTest
"11"
dockerRedis:0>get incrTest
"11"
dockerRedis:0>decr incrTest
"10"
dockerRedis:0>decrby incrTest 5
"5"
dockerRedis:0>mset set01 1 set02 2 set03 3
"OK"
dockerRedis:0>mget set01 set02 set03
1) "1"
2) "2"
3) "3"

list list type

The list type can store ordered and repeatable elements to get the elements near the head or tail The record is an extremely fast list with a maximum number of elements of 2^32-1 (4 billion)

Common commands

key to their corresponding values.
set key value NX PX 3000 atomic operation, px sets the number of milliseconds
##lpushlpush key v1 v2 v3. ..Insert list from the left sidelpoplpop keyRemove from the left side of the listrpushrpush key v1 v2 v3 ...Insert list from the rightrpoprpop keyGet it from the right side of the listlpushxlpushx key valueInsert the value into the head of the list blpopblpop key timeout Take it from the left side of the list and block when the list is empty. You can set the maximum blocking time in seconds. llenllen keyGet the number of elements in the listlrangelrange key start endReturns the elements in the specified range in the list. The range is specified by start and end##lsetrpoplpushrpushxbrpop lindexltrim##brpoplpushbrpoplpushPop from the right side of the key1 list and insert it into the left side of the key2 list, which will block key1 key2linsertlinsert key BEFORE/AFTER pivot valueInsert value into the list before or after the value pivotApplication scenario
Command name Command format Command description
lset key index value Set the element at the index position of the list to the value of value
rpoplpush key1 key2 Pop up from the right side of the key1 list And insert it to the left side of the key2 list
rpushx key Insert the value to the end of the list value
blpop key Take it out from the right side of the list and block when the list is empty. You can set the maximum blocking timeout in seconds
lindex key value Get the element whose subscript is index in the list, index starts from 0 index
ltrim key start end Trim the list and only keep the start to end range end

1 , Stack (stack) = LPUSH LPOP
  • 2, Queue (queue) = LPUSH RPOP
  • ##3, Blocking MQ (blocking queue) = LPUSH BRPOP

  • 4, user list, product list, comment list

  • set set type

  • Set: unordered, The maximum number of members in a unique element set is 2^32 - 1

Common commands

Command nameCommand format##saddsadd key value1 value2 .... Store elements into the collection key. If the element exists, it will be ignored. If the key does not exist, create a new one. sremsrem key value1 value2 ....Delete elements from the collection keysmemberssmembers keyGet all elements in the collectionspopspop key countSelect count elements from the set key, and delete the elements from the keysrandmembersrandmember key countSelect count elements from the set key, and the elements will not be deleted from the keyscardscard keyGet the number of elements in the collection keysismembersismember key memberJudge whether the member element exists in the collection keysintersinter key1 key2 key3Find the intersection of multiple setssdiffsdiff key1 key2 key3Find the difference of multiple setssunionsunion key1 key2 key3Find the difference of multiple sets Union

Application Scenario

  • WeChat Lottery Mini Program

  • ##Weibo likes, collections, tags

  • Weibo WeChat follow model

  • E-commerce product screening

zset ordered set type

SortedSet(ZSet) Ordered set: The elements themselves are unordered and non-repeating. Each element is associated with a score (score), which can be sorted by score. The score can be repeated.

Common commands

Command description
Command nameCommand formatCommand description##zaddzremzcardzcountzincrby##zscorezscore key member Return the score of the element member in the ordered set keyzrankzrank key memberGet the score of the member in the set Ranking (from small to large by score)zrangezrange key start endGet the ordered set key in positive order from start subscript to The element with stop subscriptzrevrankzrevrank key memberGet the ranking of the member in the set (from large to small by score)zrevrange zrevrange key start endGet the elements of the ordered set key from the start subscript to the stop subscript in reverse orderApplication scenarios
zadd key score1 member1 score2 member2 ... Add scored elements to the ordered set key
zrem key mem1 mem2.... From Delete elements from the ordered set key
zcard key Get the number of elements in the ordered set
zcount key min max Returns the number of elements in the collection whose score value is in the [min,max] interval
zincrby key increment member is the score of the element member in the ordered set key plus increment

Click rankings, sales rankings, attention rankings

  • hash type
Redis hash is a mapping table of string type fields and values, which provides mapping of fields and field values. Each hash can store 2^32-1 key-value pairs (more than 4 billion).

In-depth analysis of the data structure in Redis and talk about application scenarios

Advantages
  • 1. Similar data are classified and integrated for storage to facilitate data management
    • 2. Compared with string operations, it consumes less memory and CPU.
    • 3. Compared with string storage, it saves space.
    Disadvantages
  • 1. The expiration function cannot be used on fields, but can only be used on keys
    • 2. The Redis cluster architecture is not suitable for large-scale use
  • Common commands

##Command nameCommand format##hsethset key field valueStoring the key value of a hash table keyhmsethmset key field1 value1 field2 value2In a hash table Store multiple key-value pairs in keyhgethget key fieldCheck whether a field existshmgethmget key field1 field2 ...Get a field valuehsetnxhsetnx key field valueStorage the key value of a non-existent hash table keyhexistshexists key filedDetermine whether filed Existhgetallhgetall keyGet multiple field valueshdelhdel key field1 field2...Delete the specified fieldhincrbyhincrby key field incrementSpecify the field since Increase incrementhlenhlen keyGet the number of fields Application scenarios
Command description

Object cache

  • Shopping cart operation

  • bitmap bitmap type

    Bitmap performs bit operations to represent the value or status corresponding to an element through a bit, and the key is the corresponding element itself. Bitmap itself will greatly save storage space.

Commonly used commands

Command name

Command formatCommand descriptionsetbitsetbit key offset valueSet the bit value of key at offset (can only be 0 or 1). getbitgetbit key offsetGet the bit value of key at offsetGet the number of key bits that are 1Return the first index value that is set as a bit valuePerform logical operations on multiple keys and store them in destkey
##bitcount bitcount key
bitpos bitpos key value
bitop bitop and[or/xor/not] destkey key [key ...]

Application Scenario

  • 1. Users check in every month, the user ID is key, and the date is used as offset 1 to indicate check-in
  • 2. Statistics are active User, the date is the key, the user ID is offset 1, which means active
  • 3. Query the user's online status, the date is the key, the user ID is offset 1, it means online

geolocation type

geo is used by Redis to process location information. Officially used in Redis3.2. Mainly using Z-order curve, Base32 encoding and geohash algorithm

Common commands

##geoaddgeoadd key longitude latitude member name 1 longitude 1 latitude 1 member name 2 longitude 2 latitude 2 ...Add geographic coordinatesgeoposgeopos key member name 1 member name 2...Return member latitude and longitudegeodist geodist key member 1 member 2 unitCalculate the distance between membersgeoradiusbymembergeoradiusbymember key member value unit count number asc [desc]Find nearby members based on membersgeohashgeohash key member name 1 member name 2...Return standard geohash string
Command name Command format Command description



##Application scenario

1. Record geographical location

2. Calculate distance

3. Find "people nearby"

stream data flow type

stream is a new data structure after Redis5.0, used for persistent message queues .

Almost meets all the content of the message queue, including:

Serialization generation of message ID
  • Message traversal
  • Blocking of messages And non-blocking reading
  • Group consumption of messages
  • Processing of unfinished messages
  • Message queue monitoring
  • Each Stream has a unique The name, which is the key of Redis, is automatically created when the xadd command is used for the first time to append a message

Application scenarios

Usage of message queue

More For programming-related knowledge, please visit:

Introduction to Programming

! !

The above is the detailed content of In-depth analysis of the data structure in Redis and talk about application scenarios. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete