Today review Redis, five kinds of data structure and the use of various data structure comb again, here to record, see if there is any you don’t know it

String – string

Redis is the most basic of the five data types. Each key corresponds to a value.Copy the code

Common commands

127.0.0.1:6379> set wangxiaoer wangxiaoer // Store string key-value pair OK 127.0.0.1:6379> mset Wang Wang xiao xiaoer er // Store string key-value pair OK in batches 127.0.0.1:6379> keys * // Obtain all keys 1) "er" 2) "xiao" 3) "wang" 4) "wangxiaoer" 127.0.0.1:6379> setnx wang wang (INTEGER) 0 127.0.0.1:6379> keys * 1) "er" 2) "xiao" 3) "wang" 4) "wangxiaoer" 127.0.0.1:6379> (integer) 1 127.0.0.1:6379> keys * 1) "er" 2) "xiao" 3) "wangwang" 4) "Wang" 5) "wangxiaoer" 127.0.0.1:6379> get wangxiaoer // Get a string key value "wangxiaoer" 127.0.0.1:6379> mget wangxiaoer // EXPIRE wangwang 1) "Wang" 2) "Xiao" 3) "ER" 127.0.0.1:6379> EXPIRE wangwang 5 // Set the expiration time of a certain key value in seconds (integer) 1 1) "er" 2) "xiao" 3) "wangwang" 4) "wang" 5) "wangxiaoer" 127.0.0.1:6379> keys * // 1) "er" 2) "xiao" 3) "wang" 4) "wangxiaoer" 127.0.0.1:6379> set wangwangwang 1 OK 127.0.0.1:6379> Keys * 1) "er" 2) "xiao" 3) "wang" 4) "wangwangwang" 5) "wangxiaoer" 127.0.0.1:6379> INCR wangwangwang (integer) 2 127.0.0.1:6379> INCR Wangwangwang (integer) 3 127.0.0.1:6379> get Wangwangwang "3" 127.0.0.1:6379> INCRBY Wangwangwang 5 // Is the corresponding number stored by the key +5 (integer) 8 127.0.0.1:6379> Get wangwangwang "8" 127.0.0.1:6379> INCR wangxiaoer // (Error) ERR Value is not an integer or out of range 127.0.0.1:6379> DECR Wangwangwang // Indicates the corresponding value of the key store -1 (integer) 7 127.0.0.1:6379> Get wangwangwang "7" 127.0.0.1:6379> DECRBY wangwangwang 5 // Is the corresponding value of the key storage -5 (integer) 2 127.0.0.1:6379> get wangwangwang "2" 127.0.0.1:6379> help @string // Use help + @ to obtain the APPEND key value command of the data type // Summary: Append a value to a key (either numeric or string values) Summary: Count set bits in a string since: Server BITFIELD key [GET type offset] [the 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: Perform bitwise operations between strings since: 2.6.0 BITPOS key bit [start] [end] Find first bit set or clear in a string since: 2.8.7 DECR key Decrement The integer value of a key by one since: 1.0.0 DECRBY key Decrement // 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 GETBIT key offset summary: Returns the bit value at offset in the string value stored at key since: 2.2.0 GETRANGE key start end // Obtain the length of the key stored. Summary: Get a substring of the string stored at a key since: 2.4.0 GETSET key value // Obtain the existing key value and set the new value summary: Set the string value of a key and return its old value since: 1.0.0 INCR key Increment the integer value of a key by one since: 1.0.0 INCRBY key Increment Increment the integer value of a key by the given amount since: 1.0.0 INCRBYFLOAT Key increment // Add key increment 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.0mset key value [key value...] Summary: Set multiple keys to multiple values since: 1.0.1msetnx key value [key value...] Summary: Set multiple keys to multiple values, only if none of the keys exist since: PSETEX key milliseconds value // Set the value and expiration in milliseconds of a key since: Server SET key value [expiration EX seconds | PX milliseconds] [NX | XX] / / SET have the keys of the expiration date of the summary: Set the string value of a key since: 1.0.0 SETBIT Key offset Sets or clears the bit at offset in the string value stored at key since: 2.2.0 SETEX key seconds value // Add non-existent key/value pairs and Set expiration time summary: Set the value and expiration of a key since: Summary: Set the value of a key, only if the key does not exist since: 1.0.0 SETRANGE key offset value // Replaces the string in the specified range with the specified value summary: Overwrite part of a string at key starting at the specified offset since: Get the length of the value stored in a key since: 2.2.0Copy the code

Common scenarios: single-value cache: can save strings, numbers, picture information, url and other information; Object cache: Holds the JSON data of an object, or the values of various attributes of an object

Set user:1 value(data in JSON format) mset user:1:name Wangxiaoer user:1:age 18 mget user:1:name user:1:ageCopy the code

Simple distributed locks:

Setnx user:1 true // If the value is set successfully, 1 is returned; if the value fails to be set, 0 is returned. Run the service code. // If the value is set successfully, run del user:1 // Delete the lockCopy the code

Counter: the number of times the article is read, liked and viewed on wechat public account

Incrby article: XXXX :read // Read incrby article: XXXX :praise // Praise incrby article: XXXX :share //Copy the code

Distributed system global serial number: it is stored in the local memory for use, and then obtained after use

Incrby serialUID 1000 // Take more values at a time to save redis performanceCopy the code

Hashing

The key value is a map, and the value itself is a map. The structure is as follows:

Common commands Commands start with h:

127.0.0.1:6379> hset User name wangxiaoer // Store a hash table key value (integer) 1 127.0.0.1:6379> hsetnx user name wangxiaoer // Key value for storing a non-existent hash table key (integer) 0 127.0.0.1:6379> hset user age 18 (integer) 1 127.0.0.1:6379> hset user gender Male (integer) 1 127.0.0.1:6379> hget user name // Obtain the filed value "wangxiaoer" of the key in the hash table 127.0.0.1:6379> HSETNX user1 name Xiaoer (integer) 1 127.0.0.1:6379> HMSET user1 age 18 gender male OK 127.0.0.1:6379> hlen user (integer) 3 127.0.0.1:6379> HGETALL user // Obtain all hash key values 1) "name" 2) "wangxiaoer" 3) "age" 4) "18" 5) "gender" 6) "\xe7\x94\ XB7 "127.0.0.1:6379> HINCRBY user age 12 (integer) 30 127.0.0.1:6379> hmset user 1:name Wang 1:age 18 2:name xiao 2:age 19 // Batch setting OK 127.0.0.1:6379> HGETALL User 1) "1:name" 2) "wang" 3) "1:age" 4) "18" 5) "2:name" 6) "xiao" 7) "2:age" 8) "19" 127.0.0.1:6379> Help @hash // HDEL key field [field...] // Batch Delete key values of key filed in the hash table summary: Delete one or more hash fields since: 2.0.0hexists key field // Determine whether the filed in the hash table has a key summary: Determine if a hash field exists since: 2.0.0hget key field // Obtain the key value of filed in the hash table summary: Get the value of a hash field since: Summary: Get all the fields and values in a hash since: 2.0.0 HINCRBY key field increment // Add increment summary to the field values in the Hash table: Increment the integer value of a hash field by the given number since: 2.0.0 HINCRBYFLOAT Key field increment // Add INCREMENT to the number keys corresponding to the filed in the Hash table summary: Increment the float value of a hash field by the given amount since: 2.6.0 HKEYS key Get all the fields in a hash since: 2.0.0 HLEN key // Obtain the number of filed records in the hash table summary: Get the number of fields in a hash since: 2.0.0hmget key field [field...] // Batch obtain key values for filed in the hash table summary: Get the values of all the given hash fields since: 2.0.0hmset 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 // Set the key value of filed in the Hash table summary: Set the string value of a hash field since: 2.0.0 HSETNX key field Value // Set the key summary of filed that does not exist in the Hash table: Set the value of a hash field, only if the field does not exist since: 2.0.0hstrlen key field // Obtain the key length of the filed field in the hash table summary: Get the length of the value of a hash field since: 3.2.0 HVALS key // Obtain all values in the hash key (excluding filed) summary: Get all the values in a hash since: 2.0.0Copy the code

Common scenario

Object storage:

hmset user 1:name wangxiaoer 1:age 18
Copy the code

E-commerce shopping cart:

The user ID is the key, the product information is the field, and the quantity of the product is the value

Add item: hset Cart :1001 10086 1 Add item: hincrby Cart :1001 10086 1 Get total item: hlen Cart :1001 Delete item: Hdel Cart :1001 10086 Gets all items in the cart: hgetall Cart :10086Copy the code

Advantages of Hash vs. String:

Similar data classification and integrated storage, convenient data management; It consumes less memory and CPU than string operations. More space saving than string storage;Copy the code

Disadvantages:

Expiration only works on keys, not fields; Redis cluster architecture is not suitable for large-scale use (there will be data skew);Copy the code

I have a list of books

In fact, it is a linked list, and a double-ended linked list. The elements in the list are ordered, the cutting elements can be repeated, and the left and right ends of the list can be inserted and deleted. Common commands Commands usually start with l:

127.0.0.1:6379> LPUSH Wang 12 23 34 45 56 56 57 // Insert one or more values into the left header of the key list (integer) 7 127.0.0.1:6379> RPUSH Wang 75 75 65 54 43 32 21 // Insert one or more values into the end of the key list (right side) (INTEGER) 14 127.0.0.1:6379> LPOP Wang 127.0.0.1:6379> RPOP wang // insert an element from the top of the table "21" 127.0.0.1:6379> BLPOP Wang 1) "wang" 2) "56" 127.0.0.1:6379> BRPOP wang 5 1) "wang" 2) "32" 127.0.0.1:6379> LRANGE wang 0-1 Footer to 1) 1) "56" 2) "45" 3) "and" 4) "23" 5) "12" 6) "75" 7) "75" 8) "65" 9) "54" 10) "43" 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 // Insert an element from the end of a list into the head of another list. 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 Get an element from a list by its index since: 1.0.0 LINSERT key BEFORE | AFTER the pivot value / / in the front or rear of the insert a value specified elements the summary: Insert an element before or after another element in a list since: 2.2.0 LLEN key Get the length of a list since: 1.0.0 LPOP key Summary: Remove and Get the first element in a list since: LPUSH key value [value...] Summary: Prepend one or multiple values to a list since: 1.0.0 LPUSHX key value Prepend a value to a list, only if the list exists since: Summary: Get a range of elements from a list since: Summary: Remove elements from a list since: 1.0.0 LREM key count value 1.0.0 LSET key index value // Set the index value of the linked list to the specified value. Set the value of an element in a list by its index since: 1.0.0 LTRIM key start stop 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.0rpoplpush source destination // Insert an element from the end of one list into the header of another list 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.0Copy the code

Common scenarios Common data structures:

Stack: LPUSH + LPOP Queue: LPUSH + RPOP Blocking Queue: LPUSH + BRPOPCopy the code

Message flow (stack) of Twitter or subscription numbers: the first received messages are placed behind, and the last received (latest) messages are placed first

4, set

Like list, it stores multiple elements, except that elements cannot be repeated, elements are unordered, and common commands for interset operations (intersection, union, difference) are supported

127.0.0.1:6379> SADD Wang 12 12 12 12 23 34 45 56 // Add one or more elements to the set (duplicate elements will be removed) (integer) 5 127.0.0.1:6379> SREM Wang 12 1) "23" 2) "34" 3) "45" 4) "56" 127.0.0.1:6379> SCARD wang // Obtain the number of elements in the set (integer) 4 127.0.0.1:6379> SISMEMBER Wang 12 // Determine whether elements in the set (integer) 0 127.0.0.1:6379> SISMEMBER wang 23 (integer) 1 127.0.0.1:6379> SRANDMEMBER Wang 2 1) "34" 2) "23" 127.0.0.1:6379> SRANDMEMBER Wang 2 1) "45" 2) "23" 127.0.0.1:6379> SPOP Wang 2 1) "45" 2) "34" 127.0.0.1:6379> SADD Xiaoer 12 23 34 56 67 78 (integer) 6 127.0.0.1:6379> SINTER Wang Xiaoer (integer) 2 127.0.0.1:6379> SRANDMEMBER Wangxiaoer 3 1) "23" 2) "56" 127.0.0.1:6379> SUNION wang xiaoer // Select 1) "12" 2) "23" 3) "34" 4) "56" 5) "67" 6) "78" 127.0.0.1:6379> Empty list or set 127.0.0.1:6379> help @set SADD key member [member...] Summary: Add one or more members to a set since: 1.0.0 SDIFF key [key...] Summary: Multiple sets since: 1.0.0 SDIFFSTORE Destination key [key...] Summary: Subtract multiple sets and store the resulting set in a key since: SINTER key [key... 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: 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: SREM key member [member...]  summary: Remove one or more members from a set since: 1.0.0 SSCAN key cursor [MATCH pattern] [COUNT COUNT] Incrementally iterate Set elements since: 2.8.0 SUNION key [key...] Summary: Add multiple sets since: 1.0.0 SUNIONSTORE destination key [key...] // Take the intersection of the two sets and store it as a new set summary: Add multiple sets and store the resulting set in a key since: 1.0.0Copy the code

Common scenarioLucky draw applet:

SMEMBERS Lottery draws 2 people from the lottery pool. SRANDMEMBER Lottery 2 draws 2 people from the lottery pool. SRANDMEMBER Lottery 2 draws 2 people from the lottery pool. SPOP lottery 2Copy the code

Wechat likes tag:

SADD like:article001 userId Unlike: SREM like:article001 userId Check whether the user has been liked: SISMEMBER like:article001 userId SMEMBERS like:article001 SMEMBERS like:article001 SMEMBERS like:article001Copy the code

Weibo attention model:

Wangxiaoer receives attention from: SMEMBERS wangxiaoer receives attention from: SINTER Wangxiaoer Gaoyuanyuan who receives the attention of Wangxiaoer and Gaoyuanyuan who also pays attention to Gaoyuanyuan: SISMEMNER zhangziyi gaoyuanyuan obtains people wangxiaoer may know: SDIFF gaoyuanyuan wangxiaoerCopy the code

Commodity screening:

Add brand: SADD Brand: Huawei MATe40 Add old and new: SADD OldNew: New Mate40 Add size: SADD Size :6.1 Mate40 Obtain huawei's new 6.1 storage phone: SINTER brand: huawei oldnew: new size: 6.1Copy the code

Five, ordered set – zset

An ordered set is a special set, which retains the property that elements in the set cannot be repeated. The difference is that elements in the set can be sorted. Common commands Commands usually start with Z:

127.0.0.1:6379> ZADD Wang 1 Wang 2 xiao 3 er // Add the specified score value to the set (integer) 3 127.0.0.1:6379> ZREM Wang wang // Remove the specified element from the set (integer) 1 127.0.0.1:6379> ZSCORE wang xiao // Get the score value of the specified element in the set "2" 127.0.0.1:6379> ZINCRBY Wang 3 Xiao // Add the specified value to the specified element in the set "5" 127.0.0.1:6379> ZCARD wang // Obtain the number of elements in the set (integer) 2 127.0.0.1:6379> ZRANGE wang 12 // Obtain the range of elements in the set (positive order) 1) 127.0.0.1:6379> ZREVRANGE wang 0 1) "xiao" 2) "er" 127.0.0.1:6379> ZADD xiao 3 xiao 5 er (integer) 2 127.0.0.1:6379> ZINTERSTORE wangxiao 2 Wang Xiao // Get the intersection of the elements in the two sets and store (integer) 2 127.0.0.1:6379> ZRANGE Wangxiao 0-1 1) "er" 2) "xiao" 127.0.0.1:6379> help @sorted_set BZPOPMAX key [key...] Timeout // Remove the element with the highest score from one or more sets and block (specified time) if not Remove and return the member with the highest score from one or more sorted sets, Or block until one is available since: 5.0.0bzpopmin key [key...] Timeout // Remove the element with the lowest score from one or more sets and block (specified time) if none 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.0zcount key min Max // The number of elements in the specified score range Count the members in a sorted set with scores within the given values since: Summary: increment the score of a member in a sorted set since: 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 // The number of elements in the specified dictionary range Count the number of members in a sorted set between a given lexicographical range since: ZPOPMAX key [count] // Remove the maximum number of values in the specified set summary: Remove and return members with the highest scores in a sorted set since: 5.0.0 ZPOPMIN key [count] // Remove set 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] Return a range of members in a sorted set, by lexicographical range since: ZRANGEBYSCORE key min Max [WITHSCORES] [LIMIT offset count] 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] Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings. since: ZREVRANGEBYSCORE key Max min [WITHSCORES] [LIMIT offset count] Return a range of members in a sorted set, by score, with scores ordered from high to low since: 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: 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: 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.0Copy the code

Common scenarioList:

Click on news: ZADD HostNews :20201108 1 Telangpu to obtain the top 10 news of a certain day: ZREVRANGE HostNews :20201108 0 9 WITHSCORESCopy the code

Note: the key of redis is SDS (Simple Dynamic String: Simple Dynamic String). The length of the key is dynamically expanded. If the capacity is insufficient, the length is doubled (when the capacity reaches 1Mb, 1Mb is added each time).


Seeing is virtual, recording is real, will see the conversion for their own, come on!!