Redis commonly used data structures and application scenarios for hematemesis

1. String data type:

Common operations for strings:

  • SET key value Store key-value pairs, SET overwrites old values, regardless of type
  • MSET key value [key value ...] Batch store string key-value pairs
  • SETNX key value Store a non-existent key-value pair, if the key exists, do nothing
  • GET key Get the value corresponding to key according to key
  • MGET key [key ...] Get string key-value pairs in batches
  • DEL key Delete the key-value pair corresponding to the key
  • EXPIRE key seconds Set the valid time for the given key value

Atomic addition and subtraction

  • INCR key Add 1 to the number corresponding to the key value
  • DECR key Decrease the value stored by key by 1
  • INCRBY key increment Add increment to the key storage array
  • DECRBY key increment Subtract the increment from the array stored by the key

Application scenario:

  • Single-value cache: SET key value,GET key

  • Object Cache:
    SET user:1 value(json字符串);
    deposit: MSET user:1:name zhangsan user:1:age 10
    Take: MGET user:1:name user:1:age
    better than json format to facilitate single attribute manipulation, that better performance, the optimal choiceHASH

  • Distributed locks:
    SETNX product:10001 true// Send back 1 to indicate that the lock was successful, don't use it if there are disadvantages
    SETNX product:10001 true// Send back 0 to indicate that the lock failed
    DEL product:10001// Release the lock
    SET product:10001 true ex 10 nx// Prevent the program from being terminated unexpectedly resulting in deadlock

  • The use of counter
    WeChat public account reading usage scenarios
    reading statistics in Redis:

    • INCR article:readcount:{文章Id} Article reading statistics
    • GET article:readcount:{文章Id}
  • Distributed system unique ID generates
    INCRBY orderId 1000redis to generate serial number to improve performance.


2.HASH structure

Common operations

  • HSET key field value // Store the key value of a hash table key
  • HSETNX key field value // Store the key value of a non-existent hash table key
  • HMSET key field value [field value ...] Store multiple key-value pairs in a hash table key
  • HGET key field Get the key value of a field in a hash table
  • HMGET key field [field ...] Get the key values ​​of multiple fields in the hash table key
  • HDEL key field [field ...] Delete the field key value in the hash table key
  • HLEN key The number of fields in the hash table key
  • HGETALL key Return all key-value pairs in the hash table key
  • HINCRBY key field increment Add incremental increment to the value of the field field in the hash table key

Application scenario

  • Object storage
    HSET user:10001 name zhangsan age 10// Set object properties
    HGET user:10001 name age// Get attribute information

  • E-commerce shopping cart scenario
    Shopping cart scene
    E-commerce shopping cart data structure:

    • Use user ID as key
    • Product ID is field
    • The number of products is value

    Shopping cart operation:

    • Add product-> HSET cart:1001 10088 1
    • Increase the number->HINCRBY cart:1001 10088 1
    • Total number of products->HLEN cart:1001
    • Delete product HDEL cart:1001 10088
    • Get all items in shopping cart->HGETALL cart:1001

3.List data structure

List structure diagram

Common commands

  • LPUSH key value [value ...] Insert one or more values ​​into the head of the key list (leftmost)
  • RPUSH key value [value ...] Insert one or more values ​​into the header of the key list (far right)
  • LPOP key Remove and return the head element of the key list
  • RPOP key Remove and return the tail element of the key
  • LRANGE key start stop Returns the element of the specified interval in the key, the interval offset is specified by start and stop
  • BLPOP key [key ...] timeoutAn element pops up from the head of the key. If there is no element in the key, it will block and wait, block timeout, if timeout is 0, it means block all the time
  • BRPOP key [key ...] timeoutAn element pops up from the end of the key table, if there is no element in the key, it will block waiting, block timeout, if timeout is 0, it will always block

Application scenario

  • Common data structures

    • Stack = LPUSH + LPOP-> FILO advanced out
    • Queue = LPUSH + RPOP-> FIFO first-in first-out
    • Blocking MQ (blocking queue) = LPUSH + BRPOP

  • Weibo and WeChat public account message flow

Schematic diagram of Weibo and WeChat message flow
The example focuses on the use of WeChat public number spare tires and Mac Talk in Redis:

  • Mac Talk released message ID 10018-> LPUSH msg:{订阅人Id} 10018
  • The spare tire said that the car released the message ID 10019->LPUSH msg:{订阅人Id} 10019
  • View the latest subscribed news, such as 6->LRANGE msg:{订阅人Id} 0 5

4.SET structure

Common commands

  • SADD key member [member ...] Put one or more members into the key, ignore if the element exists
  • SREM key member [member ...] Remove one or more members from the collection key
  • SMEMBERS key Return all elements in the collection key
  • SCARD key The number of elements in the collection key
  • SISMEMBER key member Determine if member is an element in key
  • SRANDMEMBER key [count] Randomly take count elements from the key, the elements are not deleted from the key
  • SPOP key [count] Randomly take count elements from the key and delete the elements from the key
  • SINTER key [key ...]Intersection operation
  • SINTERSTORE destination key [key ...] Store the intersection result in the new collection destination
  • SUNION key [key ...] Union operation
  • SUNIONSTORE destination key [key ...]Save the union result in the new destination
    - SDIFF key [key ...]difference operation,

Application scenario

  • Lottery model
    Lottery model
    The use of participating lotteries in Redis in the example:
    • Click to participate in the draw to join the collection-> SADD key {userId}
    • View all users participating in the draw->SMEMBERS key
    • Draw count winners->SRANDMEMBER key [count]/SPOP key [count]

  • Like, follow and collect on Weibo and WeChat

Like and follow the collection model
The use of the like model in Redis in the example:

  • Like->SADD like:{消息id} {用户id}

  • Unlike->SREM like:{消息id} {用户id}

  • Check if the user likes->SISMEMBER like:{消息id} {用户id}

  • Get a list of liked users->SMEMBERS like:{消息id}

  • Get the number of likes->SCARD like:{消息id}

  • WeChat Weibo follow model:
    WeChat attention model
    Example WeChat follow model used in Redis:

    • People Zhang San follows->zhangsanSET->{lisi,sima,luban}
    • People Li Si Follows->lisiSET->{zhangsan,sima,luban,qiaofeng}
    • People that Wang Wu follows->wangwuSET->{zhangsan,lisi,luban,qiaofeng,duanyu}
    • People whom Zhang San and Li Si are concerned about->SINTER zhangdanSET lisiSET
    • Joe Smith also concerned about people's attention Doe -> zhangsanSET list for each member of the Watchlist to judge SISMEMBER simaSET lisi,SISMEMBER lubanSET lisi
    • People Zhang San may know->SDIFF lisiSET zhangsanSET
  • Commodity screening of collective operation e-commerce platform: the use of
    Commodity screening
    commodity screening conditions in redis:

    • SADD brand:HUAWEI p30
    • SADD brand:xiaomi mi-6X
    • SADD brand:IPhone iphone8
    • SADD os:android p30 mi-6X
    • SADD cpu:brand:intel p30 mi-6X
    • SADD ram:8G p30 mi-6X iphone8
    • SINTER os:android cpu:brand:intel ram:8G->{p30 mi-6X}

SortedSet data structure

Common commands

  • ZADD key score member [[score member] [score member] ...] Add elements with scores to the ordered combination key
  • ZREM key member [member ...] Remove key from ordered collection
  • ZSCORE key member Returns the score value of the member members in the ordered key
  • ZINCRBY key increment member Add the increment to the member element score in the ordered set key
  • ZCARD key Returns the number of elements of the ordered key
  • ZRANGE key start stop [WITHSCORES] Get elements of ordered set key from start subscript to stop subscript in positive order
  • ZREVRANGE key start stop [WITHSCORES] Get the elements of the ordered set key from start subscript to stop subscript in reverse order
  • ZUNIONSTORE destination numkeys key [key ...] Union calculation
  • ZUNIONSTORE destination numkeys key [key ...] Intersection calculation

Application scenario

  • Leaderboard scene
    Leaderboard
    The use of Weibo leaderboard in Redis:
    • Click News->ZINCRBY hotNews:20190819 1 守护香港
    • Show the top ten of the day->ZREVRANGE hotNews:20190819 0 10 WITHSCORES
    • Seven-day search list->ZUNIONSTORE hotNews:20190813-20190819 7 hotNews:20190813 hotNews:20190814 hotNews:20190815....hotNews:20190819
    • Show the top 10 on the 7th->ZREVRANGE hotNews:20190813-20190819 0 10 WITHSCORES

Insert picture description here

Published 41 original articles · Liked 14 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/Yunwei_Zheng/article/details/104976637