“This is the 22nd day of my participation in the First Challenge 2022. For details: First Challenge 2022”


  • j3_liuliang
  • Redis common API is application scenario series (List), if you feel useful can pay attention to the blogger, periodic update oh!

Related articles navigation

  1. Hyperdetailed Redis Key operation API, what? Look not to understand! You hammer me
  2. Redis String ultra detailed API usage and application scenarios introduction
  3. SCAN and related SSCAN, HSCAN, and ZSCAN commands are parsed
  4. What? The List type of Redis will not be used, see my super detailed API usage and application scenarios
  5. Redis Hash API usage and application scenarios
  6. Redis Set data type API use and illustrated application scenarios, do not see blood loss!
  7. Redis Sorted Set data type API and application scenario parsing

(1) List

The list command is divided into two categories: L (left) and R (right). As the name suggests, it is for the left operation command and the right operation command of the list. Therefore, we can know that the list data type of Redis is actually very similar to the queue, isn’t it?

For example, the fifO for a queue is lpush and then RPOP. Back in, back out is lpush and then LPOP and of course the order can be reversed depending on which direction you’re going in.

Now I’m going to use the left side as the criterion to simply draw a List operation of List

1) Add data to the city list from the left (Lpush). The data will be added from the left, and then Beijing will be squeezed step by step to the right;

2) Then start iterating from the left (lrange) over all data from 0 to -1;

3) It can be seen that the last added guabgzhou on the left will be traversed first, and the first added Beijing will be traversed last **

  • Lpush then LPOP = stack (first in, last out, last in, first out)
  • First Lpush then RPOP = queue (first in first out, last in last out)

1.1 LPUSH (LPUSH)

Inserts one or more values into the list header

The Redis Lpush command inserts one or more values into the list header. If the key does not exist, an empty list is created and an LPUSH operation is performed. An error is returned when the key exists but is not of list type.

** Note: ** LPUSH commands prior to Redis 2.4 only accept a single value.

grammar

127.0.0.1:6379 > LPUSH KEY_NAME VALUE1.. VALUENCopy the code

Version available: >= 1.0.0

Return value: The length of the list after executing LPUSH.

case

127.0.0.1:6379> flushall
OK
127.0.0.1:6379> lpush city beijing		# Add data from left, add one
(integer) 1
127.0.0.1:6379> lpush city shanghai shenzhen guangzhou	Add more data from left
(integer) 4 127.0.0.1:6379> Lrange City 0-1Start from the left and iterate over all the data
1) "guangzhou"
2) "shenzhen"
3) "shanghai"
4) "beijing"127.0.0.1:6379 >Copy the code

1.2 LPOP (LPOP)

Removes and gets the first element of the list

The Redis Lpop command is used to remove and return the first element of the list.

grammar

127.0.0.1:6379 > LLEN KEY_NAMECopy the code

Version available: >= 1.0.0

Return value: the first element of the list. Returns nil if the list key does not exist.

case

127.0.0.1:6379> Lrange City 0-1# walk through the list
1) "guangzhou"
2) "shenzhen"
3) "shanghai"
4) "beijing"127.0.0.1:6379 > lpop city# Remove an element from the left
"guangzhou"127.0.0.1:6379> Lrange City 0-1# walk through the list
1) "shenzhen"
2) "shanghai"
3) "beijing"127.0.0.1:6379 > exists namesCheck whether the key exists
(integer) 0
127.0.0.1:6379> lpop names				# Remove a value that does not exist in the list, print nil(nil) 127.0.0.1:6379 >Copy the code

1.3 LPUSHX (LPUSHX)

Inserts one or more values into an existing list header

Redis Lpushx inserts one or more values into the head of an existing list. The operation is invalid if the list does not exist.

grammar

127.0.0.1:6379 > LPUSHX KEY_NAME VALUE1.. VALUENCopy the code

Available version: >= 2.2.0

Return value: LPUSHX The length of the list after the command is executed.

case

127.0.0.1:6379 > exists cityCheck whether city exists
(integer) 1 127.0.0.1:6379> LPUSHx cityAdd value to existing list
(integer4)# success127.0.0.1:6379 > exists names# Check whether names exists
(integer) 0
127.0.0.1:6379> lpushx names j3_liuliang	Create a value for a list that does not exist
(integer) 0									# failure127.0.0.1:6379> Lrange City 0-1# Walk through the existing list (city)
1) "nanchang"'2)"shenzhen"
3) "shanghai"
4) "beijing"127.0.0.1:6379 >Copy the code

1.4 LRANGE (LRANGE)

Gets elements in the range specified by the list (closed range)

Redis Lrange returns elements within the specified range in the list, specified by the offsets START and END. Where 0 represents the first element of the list, 1 represents the second element of the list, and so on. You can also use negative subscripts, -1 for the last element of the list, -2 for the next-to-last element of the list, and so on.

grammar

127.0.0.1:6379> LRANGE KEY_NAME START END
Copy the code

Version available: >= 1.0.0

Return value: a list of elements within a specified range.

case

127.0.0.1:6379 > exists city# This list exists
(integer) 1
127.0.0.1:6379> lrange city 0 0		# Loop over a data out, close the interval
1) "nanchang"
127.0.0.1:6379> lrange city 0 1		# Close the interval by iterating over two data points
1) "nanchang"
2) "shenzhen"127.0.0.1:6379> Lrange City 12# Close the interval by iterating over three data points
1) "shenzhen"
2) "shanghai"127.0.0.1:6379> Lrange city 2-1# Loop over the penultimate and first data, closed interval
1) "shanghai"
2) "beijing"127.0.0.1:6379> Lrange City 0-1To iterate through the first to the last data is to iterate through all data
1) "nanchang"
2) "shenzhen"
3) "shanghai"
4) "beijing"127.0.0.1:6379 >Copy the code

1.5 LINDEX (LINDEX)

Gets the elements in the list by index

The Redis Lindex command is used to get elements in a list by index. You can also use negative subscripts, -1 for the last element of the list, -2 for the next-to-last element of the list, and so on.

grammar

127.0.0.1:6379 > LINDEX KEY_NAME INDEX_POSITIONCopy the code

Version available: >= 1.0.0

Return value: The element in the list whose subscript is the specified index value. Returns nil if the specified index value is not in the range of the list.

case

127.0.0.1:6379 > exists cityCheck whether the list exists
(integer) 1
127.0.0.1:6379> lindex city 2		# fetch data with subscript 2, the third data on the left
"shanghai"127.0.0.1:6379 > lindex city - 1Get the data of the last subscript
"beijing"127.0.0.1:6379 > lindex city 20Get nonexistent subscript data(nil) 127.0.0.1:6379 >Copy the code

1.6 LREM (LREM)

Remove list elements

Redis Lrem removes elements in the list that are equal to the VALUE of the parameter COUNT.

The value of COUNT can be one of the following:

  • Count > 0: Searches from the top of the table to the end of the table and removes elements equal to VALUE.
  • count < 0: Search from the end of the table to the head, remove elements equal to VALUE, the absolute VALUE of COUNT.
  • Count = 0: Removes all values equal to VALUE from the table.Copy the code

grammar

127.0.0.1:6379> LREM KEY_NAME COUNT VALUE
Copy the code

Version available: >= 1.0.0

Return value: The number of elements removed. Returns 0 if the list does not exist.

case

127.0.0.1:6379> Lrange City 0-1# Data in the current list
1) "nanchang"
2) "shenzhen"
3) "shanghai"
4) "beijing"
127.0.0.1:6379> lrem city 1 beijing		Remove elements from the table header
(integer) 1
127.0.0.1:6379> lrem city -1 shenzhen	Remove elements from the end of the table
(integer) 1
127.0.0.1:6379> lrem city -1 shenzhengggg	# Remove elements that don't exist
(integer) 0 127.0.0.1:6379> Lrange City 0-1# walk through the list
1) "nanchang"
2) "shanghai"127.0.0.1:6379 >Copy the code

1.7 LLEN (LLEN)

Get the list length

The Redis Llen command is used to return the length of the list. If the list key does not exist, the key is interpreted as an empty list and 0 is returned. If the key is not a list type, an error is returned.

grammar

127.0.0.1:6379 > LLEN KEY_NAMECopy the code

Version available: >= 1.0.0

Return value: The length of the list.

case

127.0.0.1:6379> flushall OK 127.0.0.1:6379> lpush City Beijing Shanghai Shenzhen GuangzhouAdd data to the list
(integer) 5
127.0.0.1:6379> llen city			# return the list length
(integer) 5
127.0.0.1:6379> exists names		Check whether the key exists
(integer) 0
127.0.0.1:6379> llen names			# return the length of the key that does not exist
(integer) 0 127.0.0.1:6379 >Copy the code

1.8 LTRIM (LTRIM)

To trim a list, that is, to keep only elements within a specified range, and to remove all elements that are not within a specified range.

Redis Ltrim Trims a list. That is, the list is trimmed so that only elements within a specified range are left in the list. Elements outside the specified range are deleted.

The subscript 0 indicates the first element of the list, the subscript 1 indicates the second element of the list, and so on. You can also use negative subscripts, -1 for the last element of the list, -2 for the next-to-last element of the list, and so on.

grammar

127.0.0.1:6379> LTRIM KEY_NAME START STOP
Copy the code

Version available: >= 1.0.0

Return value: Ok is returned if the command is successfully executed.

case

127.0.0.1:6379> lpush names j3_liuliang xiaohong xiaoma xiaoli xiaohua xiaowang	# add data
(integer) 6 127.0.0.1:6379> Ltrim names 0-2Keep the value from the first to the penultimateOK 127.0.0.1:6379> lrange names 0-1# traversal
1) "xiaowang"
2) "xiaohua"
3) "xiaoli"
4) "xiaoma"
5) "xiaohong"127.0.0.1:6379> Ltrim names 30-2Keep the number from 30 to the next-to-lastOK 127.0.0.1:6379> lrange names 0-1# is empty
(empty list or set)
127.0.0.1:6379> lpush names j3_liuliang xiaohong xiaoma xiaoli xiaohua xiaowang # add data
(integer) 6 127.0.0.1:6379> Ltrim names 0-20Keep the number from the first to the penultimate twentiethOK 127.0.0.1:6379> lrange names 0-1# is empty
(empty list or set) 127.0.0.1:6379 >Copy the code

1.9 LINSERT (LINSERT)

Inserts an element before or after the element in the list

The Redis Linsert command is used to insert an element before or after an element in a list. When the specified element does not exist in the list, no action is performed. When the list does not exist, it is treated as an empty list and no action is performed. If the key is not a list type, an error is returned.

grammar

LINSERT KEY_NAME BEFORE EXISTING_VALUE NEW_VALUE 
Copy the code

Version available: >= 1.0.0

Return value: Returns the length of the list after the insertion, if the command executed successfully. If the specified element is not found, -1 is returned. If key does not exist or is an empty list, 0 is returned.

case

127.0.0.1:6379> Lrange City 0-1# walk through the list
1) "guangzhou"
2) "hangzhou"
3) "shenzhen"
4) "shanghai"
5) "beijing"
127.0.0.1:6379> linsert city before beijing tianjing	# Insert tianjing before Beijing
(integer) 6 127.0.0.1:6379> Lrange City 0-1# Walk through the list to see the effect
1) "guangzhou"
2) "hangzhou"
3) "shenzhen"
4) "shanghai"
5) "tianjing"
6) "beijing"
127.0.0.1:6379> linsert city after guangzhou dongwan		Insert dongwan behind Guangzhou
(integer) 7 127.0.0.1:6379> Lrange City 0-1# Walk through the list to see the effect
1) "guangzhou"
2) "dongwan"
3) "hangzhou"
4) "shenzhen"
5) "shanghai"
6) "tianjing"
7) "beijing"127.0.0.1:6379 >Copy the code

1.10 LSET (LSET)

Set the value of a list element by index

Redis Lset sets the value of an element by index.

An error is returned when an index parameter is out of range, or when LSET is performed on an empty list.

grammar

127.0.0.1:6379> LSET KEY_NAME INDEX VALUE
Copy the code

Version available: >= 1.0.0

Return value: OK is returned on success, otherwise an error message is returned.

case

127.0.0.1:6379> Lrange City 0-1# Current list data
1) "guangzhou"
2) "dongwan"
3) "hangzhou"
4) "shenzhen"
5) "shanghai"
6) "tianjing"
7) "beijing"
127.0.0.1:6379> lset city 0 guangzhou1111	Change the index 0 to guangzhou1111OK 127.0.0.1:6379> lrange city 0-1# Walk through the list to see the effect
1) "guangzhou1111"
2) "dongwan"
3) "hangzhou"
4) "shenzhen"
5) "shanghai"
6) "tianjing"
7) "beijing"
127.0.0.1:6379> lset city 3 shenzhen0000000	# change data subscript 3 to shenzhen0000000OK 127.0.0.1:6379> lrange city 0-1# Walk through the list to see the effect
1) "guangzhou1111"
2) "dongwan"
3) "hangzhou"
4) "shenzhen0000000"
5) "shanghai"
6) "tianjing"
7) "beijing"
127.0.0.1:6379> lset city 30 shenzhen0000000	# Set data for nonexistent subscripts
(error) ERR index out of range					Error, subscript out of bounds127.0.0.1:6379> Lrange City 0-1# list data, no change
1) "guangzhou1111"
2) "dongwan"
3) "hangzhou"
4) "shenzhen0000000"
5) "shanghai"
6) "tianjing"
7) "beijing"127.0.0.1:6379 >Copy the code

1.11 RPUSH (RPUSH)

Adds one or more values to the list

The Redis Rpush command is used to insert one or more values at the end of the list (far right).

If the list does not exist, an empty list is created and an RPUSH operation is performed. An error is returned when a list exists but is not of a list type.

** Note: ** RPUSH commands prior to Redis 2.4 only accept a single value.

grammar

127.0.0.1:6379 > RPUSH KEY_NAME VALUE1.. VALUENCopy the code

Version available: >= 1.0.0

Return value: The length of the list after the RPUSH operation.

case

127.0.0.1:6379> flushall
OK
127.0.0.1:6379> rpush city beijing shanghai guangzhou shenzhen	# Add data from left, multiple
(integer) 4
127.0.0.1:6379> rpush city hangzhou	# Add data from left, single
(integer) 5 127.0.0.1:6379> Lrange City 0-1Start from the right to iterate over the data
1) "beijing"
2) "shanghai"
3) "guangzhou"
4) "shenzhen"
5) "hangzhou"127.0.0.1:6379 >Copy the code

1.12 RPOP (RPOP)

Removes and gets the last element of the list

The Redis Rpop command is used to remove and return the last element of the list.

grammar

127.0.0.1:6379 > RPOP KEY_NAMECopy the code

Version available: >= 1.0.0

Return value: The last element of the list. Returns nil when the list does not exist.

case

127.0.0.1:6379> Lrange City 0-1# Current list data
1) "beijing"
2) "shanghai"
3) "guangzhou"
4) "shenzhen"
5) "hangzhou"127.0.0.1:6379 > rpop city# Remove data from right side (one)
"hangzhou"127.0.0.1:6379 > exists namesCheck whether the key exists
(integer) 0
127.0.0.1:6379> rpop names			Return nil if key does not exist(nil) 127.0.0.1:6379 >Copy the code

RPUSHX (RPUSHX)

Add a value to an existing list

The Redis Rpushx command is used to insert one or more values to the end (rightmost) of an existing list. If the list does not exist, the operation is invalid.

grammar

127.0.0.1:6379 > RPUSHX KEY_NAME VALUE1.. VALUENCopy the code

Available version: >= 2.2.0

Return value: The length of the list after the Rpushx operation.

case

127.0.0.1:6379> Lrange City 0-1Data in the current list
1) "beijing"
2) "shanghai"
3) "guangzhou"
4) "shenzhen"127.0.0.1:6379 > rpushx city of tianjin# Add data to existing list (starting from right)
(integer) 5 127.0.0.1:6379> Lrange City 0-1# Current list data
1) "beijing"
2) "shanghai"
3) "guangzhou"
4) "shenzhen"
5) "tianjin"127.0.0.1:6379 > exists namesCheck whether the key exists
(integer) 0
127.0.0.1:6379> rpushx names j3_liuliang	Add data to a key that does not exist
(integer) 0									# failure127.0.0.1:6379 > exists names# no changes, no data will be created
(integer) 0 127.0.0.1:6379 >Copy the code

1.14 RPOPLPUSH (RPOPLPUSH)

Removes the last element of the list and adds it to another list and returns

The Redis Rpoplpush command is used to remove the last element of a list, add it to another list and return it.

grammar

127.0.0.1:6379 > RPOPLPUSH SOURCE_KEY_NAME DESTINATION_KEY_NAMECopy the code

Version available: >= 1.0.0

Return value: the element that was ejected.

case

127.0.0.1:6379> Lrange City 0-1#city list data
1) "beijing"
2) "shanghai"
3) "guangzhou"
4) "shenzhen"
5) "tianjin"127.0.0.1:6379> lrange names 0-1# Names list data
1) "j3_liuliang"127.0.0.1:6379 > rpoplpush city names# add the last data popup in city to names
"tianjin"127.0.0.1:6379> Lrange City 0-1# View all data
1) "beijing"
2) "shanghai"
3) "guangzhou"
4) "shenzhen"127.0.0.1:6379> lrange names 0-1# View all data
1) "tianjin"
2) "j3_liuliang"127.0.0.1:6379 >Copy the code

1.15 BLPOP (BLPOP)

Removes and retrieves the first element of the list. If there are no elements in the list, the list is blocked until the wait times out or an eject element is found. Analog blocking queue

The Redis Blpop command removes and retrieves the first element of the list. If there are no elements in the list, the list will be blocked until the wait times out or a pop-up element is found.

grammar

127.0.0.1:6379> BLPOP LIST1 LIST2.. LISTN TIMEOUTCopy the code

Available version: >= 2.0.0

Return value: If the list is empty, return nil. Otherwise, a list of two elements is returned, the first being the key of the ejected element and the second the value of the ejected element.

case

127.0.0.1:6379> lrange names 0-1All data in the current list
1) "tianjin"
2) "j3_liuliang"127.0.0.1:6379 > blpop names 5If there is no data in the list, wait 5 seconds, return nil if the list has not been added by another thread, return nil immediately if other data has been added
1) "names"
2) "tianjin"127.0.0.1:6379> lrange names 0-1All data in the current list
1) "j3_liuliang"127.0.0.1:6379 > blpop names 5If there is no data in the list, wait 5 seconds, return nil if the list has not been added by another thread, return nil immediately if other data has been added
1) "names"		
2) "j3_liuliang"127.0.0.1:6379 > blpop names 50If no other data is added to names, nil is returned. If no data is added to names, nil is returned
1) "names"
2) "xiaowang"							# This is another client I opened to add data to names, so this client is immediately aware of the popup data, user 16.79 seconds(16.79 s) 127.0.0.1:6379 >Copy the code

1.16 BRPOP (BRPOP)

Removes and retrieves the last element of the list. If there are no elements in the list, the list is blocked until the wait times out or an eject element is found. Analog blocking queue

The Redis Brpop command moves out and retrieves the last element of the list. If there is no element in the list, the list is blocked until the wait times out or an eject element is found.

grammar

127.0.0.1:6379> BRPOP LIST1 LIST2.. LISTN TIMEOUTCopy the code

Available version: >= 2.0.0

Return value: If no element is ejected within the specified time, nil and wait time are returned. Instead, return a list of two elements, the first being the key of the ejected element and the second the value of the ejected element.

case

# the same as blpop, just a problem of direction, for example, see the blpop command
Copy the code

1.17 BRPOPLPUSH (BRPOPLPUSH)

Pops a value from a list, inserts the pop-up element into another list and returns it; If the list has no elements, it blocks until the wait times out or a popup element is found.

The Redis Brpoplpush command pops a value from the list, inserts the popup element into another list and returns it. If the list has no elements, it blocks until the wait times out or a popup element is found.

grammar

127.0.0.1:6379> BRPOPLPUSH LIST1 ANOTHER_LIST TIMEOUT 
Copy the code

Available version: >= 2.0.0

Return value: If no element is ejected within the specified time, nil and wait time are returned. Instead, return a list of two elements, the first being the value of the ejected element and the second being the wait time.

case

# brpoplPush is the same as rpoplpush, except that a wait time is added. If there is no data in the list, it will return nil127.0.0.1:6379 > keys * 1)"name"
2) "city"127.0.0.1:6379> lrange name 0-1#name the data in the list
1) "xiaowang"
127.0.0.1:6379> brpoplpush name city 10		# brpoplpush and rpoplpush have the same effect when there is data in name
"xiaowang"
127.0.0.1:6379> brpoplpush name city 100	Brpoplpush will block for 100 seconds and wait for data to be added to name. If there is no data after 100 seconds, return nil
"xiaoliu"(26.60 s)Wait 26 seconds for successful execution!127.0.0.1:6379 >Copy the code

2. Application scenarios

2.1 Message Queue

As shown in the figure below, the combination of Redis lpush + BRPOP commands can achieve blocking queues. The producer client uses Lpush to insert elements from the left side of the list, and multiple consumer clients use BRPOP to block elements at the end of the list. Multiple clients ensure load balancing and high availability of consumption.

2.2 the stack

This principle can be implemented by (lpush LPOP left in and left out, or Rpush RPOP right in and right out)

2.3 Latest List

Lpush and lrange commands of the list type can realize the function of the latest list. Lpush commands are used to insert new elements into the list every time, and then lrange commands are used to read the latest list of elements, such as the “like” list and “comment list” in the moments.

However, not all of the latest list can list type, frequently updated list, because for list types of pages may result in list elements to repeat or miss, for example, the current list from the header to footer has in turn (E, D, C, B, A) five elements, three elements for each page, the user first to get to (E, D, C) three elements, then add A new element F to the table header, the list becomes (F, E, D, C, B, A), then the user takes the second page to get (C, B, A), element C is repeated. Only lists that do not require pagination (such as fetching only the first five elements of the list each time) or that are updated infrequently (such as once every morning) are suitable for list implementation. For lists that need to be paged and updated frequently, use the sorted collection sorted set type. In addition, the latest list that needs to be searched by time range cannot be realized by the list type, but also needs to be realized by the sorted set type, such as the order list queried by the transaction time range. We’ll detail how the sorted set type implements the latest list later in the application scenario of the sorted set type.

2.4 list

The lrange command of type list can be paged to see the data in the queue. The ranking list calculated at intervals can be stored in the list type, such as jingdong’s daily mobile phone sales ranking, the ranking of students in each school’s monthly examination, and the ranking of hosts in Douyu’s year-end Celebration.

However, not all leaderboards can be implemented with the list type. Only the leaderboards calculated at a certain time are suitable for the list type storage. The leaderboards calculated at a certain time correspond to leaderboards calculated in real time, and the list type cannot support leaderboards calculated in real time. Later, we will introduce the application scenario of sorted set.

conclusion

  • This article is written in combination with Redis Chinese website and bloggers’ practical cases. In the next installment, I will write Hash types
  • Due to the lack of knowledge of the blogger, there will be mistakes, if you find mistakes or bias, please comment to me, I will correct it.
  • If you think the article is good, your retweets, shares, likes and comments are the biggest encouragement to me.
  • Thank you for reading. Welcome and thank you for your attention.