Redis Advanced - Core Data Structure Advanced Actual

Article Directory


If you have not yet touched Redis, please read [Redis-Getting Started to Proficiency]

Redis Basic Data Structure

Here, let's review briefly. It's enough to remember what you use most often. You can't remember to visit official websites.

Redis API

Generic API

  keys ,del ,dbsize ,expire (ttl,persist),exists,type.......

Time complexity is O(1)

strings\ hash\list\set\zset


SET  key  value 			//Save string key-value pairs
MSET  key  value [key value ...] 	//Bulk Storage of String Key-Value Pairs
SETNX  key  value 		//Save a non-existent string key-value pair
GET  key 			//Gets a string key value
MGET  key  [key ...]	 	//Bulk Get String Key Values
DEL  key  [key ...] 		//Delete a key
EXPIRE  key  seconds 		//Set the expiration time of a key (seconds)

//Atomic Addition and Subtraction
INCR  key 			//Add 1 to the number stored in the key
DECR  key 			//Reduce the number stored in the key by 1
INCRBY  key  increment 		//Add increment to the value stored by key
DECRBY  key  decrement 	//Subtract decrement from value stored in key


HSET  key  field  value 			//Stores the key value of a hash table key
HSETNX  key  field  value 		//Stores a key value for a non-existent hash table key
HMSET  key  field  value [field value ...] 	//Storing multiple key-value pairs in a hash table key
HGET  key  field 				//Gets the field key value corresponding to the hash table key
HMGET  key  field  [field ...] 		//Bulk Get Multiple field key Values in Hash Table key
HDEL  key  field  [field ...] 		//Delete field key value in hash table key
HLEN  key				//Returns the number of field s in the hash table key
HGETALL  key				//Returns all the key values in the hash table key
HINCRBY  key  field  increment 		//Add increment to the value of the field key in the hash table key


LPUSH  key  value [value ...] 		//Insert one or more value values into the header of the key list (leftmost)
RPUSH  key  value [value ...]	 	//Insert one or more value values at the end of the key list (rightmost)
LPOP  key			//Remove and return the header element of the key list
RPOP  key			//Remove and return the tail element of the key list
LRANGE  key  start  stop		//Returns the elements within a specified interval in the list key, specified by offsets start and stop
BLPOP  key  [key ...]  timeout	//Pop up an element from the header of the key list, if there are no elements in the list, block waiting. * timeout seconds, if timeout=0, block waiting all the time
BRPOP  key  [key ...]  timeout 	//Pop up an element from the end of the key list table. If there are no elements in the list, block the wait. * timeout seconds, if timeout=0, block the wait


Set Common operations
SADD  key  member  [member ...]			//Put an element into the collection key, ignoring the element if it exists.
							//New if key does not exist
SREM  key  member  [member ...]			//Remove element from collection key
SMEMBERS  key					//Gets all the elements in the collection key
SCARD  key					//Gets the number of elements of the collection key
SISMEMBER  key  member			//Determine if member element exists in collection key
SRANDMEMBER  key  [count]			//Select count elements from the set key, and do not delete elements from the key
SPOP  key  [count]				//Select count elements from the set key, delete elements from the key

Set Operational operations
SINTER  key  [key ...] 				//intersect
SINTERSTORE  destination  key  [key ..]		//Save the intersection results in a new set destination
SUNION  key  [key ..] 				//Union operation
SUNIONSTORE  destination  key  [key ...]		//Save union results in a new set destination
SDIFF  key  [key ...] 				//Difference set operation
SDIFFSTORE  destination  key  [key ...]		//Save the difference result in a new set destination


  ZSet Common operations
ZADD key score member [[score member]...]	//Add a score element to an ordered set key
ZREM key member [member ...]		//Delete element from ordered collection key
ZSCORE key member 			//Returns the score of an element member in an ordered set key
ZINCRBY key increment member		//Add increment to the score of the member of the element in the ordered set key 
ZCARD key				//Returns the number of elements in an ordered set key
ZRANGE key start stop [WITHSCORES]	//Get ordered set key s from start subscript to stop subscript elements in positive order
ZREVRANGE key start stop [WITHSCORES]	//Gets the elements of the ordered set key from the start subscript to the stop subscript in reverse order

Zset Collection Operation
ZUNIONSTORE destkey numkeys key [key ...] 	//Union calculation
ZINTERSTORE destkey numkeys key [key ...]	//Intersection calculation

Application Scenarios


Single Value Cache

SET  key  value 	
GET  key 	

Object Cache

1) SET  user:1  value (json Format data)
2) MSET  user:1:name  artisan user:1:balance  1888
  MGET  user:1:name  user:1:balance 

Distributed Lock

SETNX  product:10001  true 		//Return 1 for successful lock acquisition
SETNX  product:10001  true 		//Return 0 indicates failure to acquire lock
. . . Perform business operations
DEL  product:10001			//Execute Business Release Lock
SET product:10001 true  ex  10  nx	//Prevent programs from accidentally terminating causing deadlocks


INCR article:judge:{Article id}  	
GET article: judge:{Article id} 

Forward comments

Cluster environment concurrent access to the same article How to ensure thread security

redis single-threaded atomicity

Web Cluster session Sharing

spring session + redis for session sharing

The spring session itself uses redis as external storage

Distributed System Global Sequence Number

INCRBY  orderId  1000

Each time 1000 is fetched into memory, VS goes to redis to fetch 1 at a time

N multi-table, N multi-concurrent, N multi-scene using redis

It doesn't matter if the node hangs up, it's just a waste of IDS


Object Cache

HMSET  user  {userId}:name  artisan  {userId}:balance  1888
HMSET  user  1:name  artisan  1:balance  1888
HMGET  user  1:name  1:balance  

Timeout for key, cannot for field
Avoid big key

E-commerce shopping cart

1) Use user id as key
2) The commodity id is field
3) The quantity of goods is value

- Shopping cart operation

  1. Add Item_hset cart:1001 10088 1
  2. Increase number of hincrby carts:1001 10088 1
  3. Total number of merchandises_hlen cart:1001
  4. Delete item hdel cart:1001 10088
  5. Get all shopping cart items_hgetall cart:1001


Common data structures

 Queue = LPUSH + RPOP
 Blocking MQ = LPUSH + BRPOP (Blocking other messages, if used, using a separate Redis)

WeChat-Subscription Number Message

For example, how do I display messages sent by public numbers that I care about?

For instance
1) A 23:00 issues a public document with message ID 10018

LPUSH msg: {My-ID} 10018

2) B 23:05 issues public document with message ID 10086

LPUSH msg: {My-ID} 10086

3) C 23:30 issues public document with message ID 10099

LPUSH msg: {My-ID} 10099

3) View the latest public number announcements

LRANGE msg: {My-ID} 0 5

Put them all in my queue, lpush from the left

Article id of C Article id B Article id of A

Get it, it must be time reversed

LRANGE  msg:{My-ID}  start  stop 


Comments, collections, labels

  1. Give the thumbs-up
SADD like:{Message ID} {User ID}
  1. Cancel a favor
SREM like:{Message ID} {User ID}
  1. Check if the user has overrated
SISMEMBER like:{Message ID} {User ID}
  1. Get a list of favorite users
SMEMBERS like:{Message ID}
  1. Get some favorite users
SCARD like:{Message ID}

Luck draw

Click to participate in the lottery to join the collection
SADD key {userlD}
2) View all users participating in the lottery
3) Draw count s winners
SRANDMEMBER key [count] / SPOP key [count]

Remove SPOP from 1st, 2nd and 3rd prize draw

Concern and friends together.

Application of Collection Operations

SINTER set1 set2 set3 -> { c }
SUNION set1 set2 set3 ->  { a,b,c,d,e }
SDIFF set1 set2 set3 ->  { a }   Base on the first set minus all elements of the subsequent set
             Abc -  bcd  cde --->  a  Not counted if the first set does not exist


Hot Search

1) Click on news

ZINCRBY  hotNews:20200307  1  fujian [score plus1 ]

2) Top 10 on display day

ZREVRANGE  hotNews:20200307  0  10  WITHSCORES 

3) 7-day Search List Calculation

ZUNIONSTORE  hotNews:20200301-20200307  7 
hotNews:20200301  hotNews:202000302... hotNews:202000307

4) Show Top Ten of Seven Days

ZREVRANGE hotNews:20200301-20200307  0  10  WITHSCORES
821 original articles published. 2,053 approved. 4.18 million visits+
His message board follow

Tags: Redis Session Spring JSON

Posted on Thu, 12 Mar 2020 20:56:21 -0400 by Jona