1. String data type:
Common operations for strings:
SET key value
Store key-value pairs, SET overwrites old values, regardless of typeMSET key value [key value ...]
Batch store string key-value pairsSETNX key value
Store a non-existent key-value pair, if the key exists, do nothingGET key
Get the value corresponding to key according to keyMGET key [key ...]
Get string key-value pairs in batchesDEL key
Delete the key-value pair corresponding to the keyEXPIRE 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 valueDECR key
Decrease the value stored by key by 1INCRBY key increment
Add increment to the key storage arrayDECRBY 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
reading statistics in Redis:INCR article:readcount:{文章Id}
Article reading statisticsGET article:readcount:{文章Id}
-
Distributed system unique ID generates
INCRBY orderId 1000
redis to generate serial number to improve performance.
2.HASH structure
Common operations
HSET key field value
// Store the key value of a hash table keyHSETNX key field value
// Store the key value of a non-existent hash table keyHMSET key field value [field value ...]
Store multiple key-value pairs in a hash table keyHGET key field
Get the key value of a field in a hash tableHMGET key field [field ...]
Get the key values of multiple fields in the hash table keyHDEL key field [field ...]
Delete the field key value in the hash table keyHLEN key
The number of fields in the hash table keyHGETALL key
Return all key-value pairs in the hash table keyHINCRBY 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
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
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 listRPOP key
Remove and return the tail element of the keyLRANGE key start stop
Returns the element of the specified interval in the key, the interval offset is specified by start and stopBLPOP key [key ...] timeout
An 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 timeBRPOP key [key ...] timeout
An 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
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 existsSREM key member [member ...]
Remove one or more members from the collection keySMEMBERS key
Return all elements in the collection keySCARD key
The number of elements in the collection keySISMEMBER key member
Determine if member is an element in keySRANDMEMBER key [count]
Randomly take count elements from the key, the elements are not deleted from the keySPOP key [count]
Randomly take count elements from the key and delete the elements from the keySINTER key [key ...]
Intersection operationSINTERSTORE destination key [key ...]
Store the intersection result in the new collection destinationSUNION key [key ...]
Union operationSUNIONSTORE destination key [key ...]
Save the union result in the new destination
-SDIFF key [key ...]
difference operation,
Application scenario
- 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]
- Click to participate in the draw to join the collection->
- Like, follow and collect on Weibo and WeChat
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:
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
- People Zhang San follows->
-
Commodity screening of collective operation e-commerce platform: the use of
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 keyZREM key member [member ...]
Remove key from ordered collectionZSCORE key member
Returns the score value of the member members in the ordered keyZINCRBY key increment member
Add the increment to the member element score in the ordered set keyZCARD key
Returns the number of elements of the ordered keyZRANGE key start stop [WITHSCORES]
Get elements of ordered set key from start subscript to stop subscript in positive orderZREVRANGE key start stop [WITHSCORES]
Get the elements of the ordered set key from start subscript to stop subscript in reverse orderZUNIONSTORE destination numkeys key [key ...]
Union calculationZUNIONSTORE destination numkeys key [key ...]
Intersection calculation
Application scenario
- Leaderboard scene
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
- Click News->