“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

You have to work really hard to look effortless!

Wechat search public number [long Coding road], together From Zero To Hero!

preface

In the last article, we introduced some of the commands in Redis. In this article, we continue to learn the rest of the commands, if you forgot the last command, you can review them first.

LLEN

Available versions: >= 1.0.0

Time complexity: O(1)

The command format

LLEN key
Copy the code

Command description

  • Return list length
  • If the list does not exist, return 0
  • If the type of value corresponding to the key is not a list, error is returned

The return value

Integer: list length

The sample

127.0.0.1:6379> lpush mylist world
(integer) 1
127.0.0.1:6379> lpush mylist hello
(integer) 2
127.0.0.1:6379> llen mylist
(integer) 2

#The key does not exist
127.0.0.1:6379> llen notexistkey
(integer) 0

#Value type is not a list, llEN error127.0.0.1:6379> Set key1 value1 OK 127.0.0.1:6379> LLEN KEY1 (error) WRONGTYPE Operation against a key holding the wrong  kind of valueCopy the code

LREM

Available versions: >= 1.0.0

Time complexity: O(N+M), where N is the length of the list and M is the number of elements to remove

The command format

LREM key count element
Copy the code

Command description

  • According to the given parameterselement, remove the front from the listcountwithelementEqual elements
  • Count >0: the table is removed from the header to the tail
  • Count <0: the table is removed from the tail to the head
  • Count =0: Removes all elements equal to element from the list
  • LREM list -2 "hello"Equivalent to removinglistThe last two in thehello

The return value

Integer: number of removed elements (return 0 if key does not exist)

The sample

127.0.0.1:6379> rpush lLENList Hello (INTEGER) 1 127.0.0.1:6379> rpush llenList Hello (INTEGER) 2 127.0.0.1:6379> rpush Llenlist world (INTEGER) 3 127.0.0.1:6379> rpush lLenList Hello (INTEGER) 4 127.0.0.1:6379> rpush lLenList Hello (INTEGER) 5 127.0.0.1:6379> lrange llenList 0-1 1) "hello" 2) "hello" 3) "world" 4) "hello" 5) "hello"
#If count>0, remove from the table header127.0.0.1:6379> lrem llenList 1 hello (INTEGER) 1 127.0.0.1:6379> lrange llenList 0-1 1) "hello" 2) "world" 3) "hello" 4) "hello"
#If count<0, remove from the end of the table127.0.0.1:6379> lrem llenList-1 hello (INTEGER) 1 127.0.0.1:6379> lrange llenList 0-1 1) "hello" 2) "world" 3) "hello"
#If count=0, remove all specified elements127.0.0.1:6379> lrem llenList 0 hello (INTEGER) 2 127.0.0.1:6379> lrange llenList 0-1 1) "world"Copy the code

LINSERT

Available version: >= 2.2.0

Time complexity: O(N), N is the number of elements to traverse to the specified element, pivot is O(1), and tail is O(N).

The command format

LINSERT key BEFORE|AFTER pivot element
Copy the code

Command description

  • Values an elementelementInserts the specified element into the listpivotBefore or after
  • If the key does not exist, no operation is performed
  • If the type of value corresponding to the key is not a list, error is returned

The return value

Integer: the length of the list after inserting the element (-1 if no pivot is found)

The sample

127.0.0.1:6379> rpush insertlist hello
(integer) 1
127.0.0.1:6379> rpush insertlist world
(integer) 2
127.0.0.1:6379> lrange insertlist 0 -1
1) "hello"
2) "world"

#Before inserting
127.0.0.1:6379> linsert insertlist before hello my
(integer) 3
127.0.0.1:6379> lrange insertlist 0 -1
1) "my"
2) "hello"
3) "world"

#After inserting
127.0.0.1:6379> linsert insertlist after world end
(integer) 4
127.0.0.1:6379> lrange insertlist 0 -1
1) "my"
2) "hello"
3) "world"
4) "end"

#Specifies that pivot does not exist
127.0.0.1:6379> linsert insertlist after name lifelmy
(integer) -1
Copy the code

LSET

Available versions: >= 1.0.0

Time complexity: O(N), where N is the length of the list, or O(1) if the index is set to header or tail.

The command format

LSET key index element
Copy the code

Command description

  • The index forindexIs set toelement
  • Index out of list range, return error

The return value

String: “OK”

The sample

127.0.0.1:6379> lpush mylist world
(integer) 1
127.0.0.1:6379> lpush mylist hello
(integer) 2
127.0.0.1:6379> lrange mylist 0 -1
1) "hello"
2) "world"

#Set index 0127.0.0.1:6379> lset myList 0 west OK 127.0.0.1:6379> lrange myList 0-1 1) "west" 2) "world"
#Out of list
127.0.0.1:6379> lset mylist 3 test
(error) ERR index out of range
Copy the code

LPOS

Available version: >= 6.0.6

Time complexity: O(N), N is the number of specified elements in the list.

The command format

LPOS key element [RANK rank] [COUNT num-matches] [MAXLEN len]
Copy the code

Command description

  • Return the specified elementelementIndex in a list
  • If no parameter is specified, the first matching index is returned by default. If there’s no match, return nil
> RPUSH mylist a b c 1 2 3 c c
> LPOS mylist c
2
Copy the code
  • Optional parametersrank: Returns the row when there are more than one match in the listrankA matching index. whenrankIf the value is positive, the index is returned from the table header to the table tail. whenrankIf the value is negative, search from the tail to the head of the table
  • No matterrankIs a positive or negative number, and the index returned is always a positive number, that is, an index starting with 0
#Returns the index of the second match
> LPOS mylist c RANK 2
6

#The search starts at the end of the table and returns the first index that matches
> LPOS mylist c RANK -1
7
Copy the code
  • Optional parameterscount : returns multiple matched indexes; Count =0 indicates that all matching indexes are returned
> LPOS mylist c COUNT 2[2, 6]
> LPOS mylist c COUNT 0[2, 6]Copy the code
  • rank + countFrom the first:rankStart with a matched index, returncountindex
> LPOS mylist c RANK -1 COUNT 2[7]Copy the code
  • If an optional parameter is provided when no value is matchedcount, returns an empty array; Otherwise returnsnil
  • Optional parametersMAXLEN: access the list at mostMAXLENTo compare elements,0Traversal of all element comparisons

The return value

No optional arguments: return element index or nil (element does not exist)

Provide the count argument: return the array

The sample

127.0.0.1:6379> rpush mykey a b c d a b c a
(integer) 8

#The default starts at the table header
127.0.0.1:6379> lpos mykey a
(integer) 0

#The rank argument, starting from the table header, returns the second index to match
127.0.0.1:6379> lpos mykey a rank 2
(integer) 4

#The rank argument, which starts at the end of the table and returns the second index that matches127.0.0.1:6379> lpos mykey a rank-2 (INTEGER) 4
#Specifies the count parameter to return multiple matching indexes
127.0.0.1:6379> lpos mykey a count 3
1) (integer) 0
2) (integer) 4
3) (integer) 7

#Rank +count, return 3 indexes from the second match (no more matches, only 2)
127.0.0.1:6379> lpos mykey a rank 2 count 3
1) (integer) 4
2) (integer) 7
Copy the code

LTRIM

Available versions: >= 1.0.0

Time complexity: O(N), where N is the number of elements removed

The command format

LTRIM key start stop
Copy the code

Command description

  • A list is truncated to keep the elements in a given range, and the rest of the elements are deleted
  • startstopCan be positive or negative: positive means start at the top (index 0), negative means start at the bottom (index -1)
  • No error is reported when a given parameter is out of the list:
    • startOut of the list orstart > stopThe result is an empty list
    • stopBeyond the scope of the list, the processing of the element ends

The return value

String: “OK”

The sample

127.0.0.1:6379> rpush myList a b c d e (INTEGER) 5 127.0.0.1:6379> ltrim myList 1 3 OK 127.0.0.1:6379> lrange myList 0 -1 1) "b" 2) "c" 3) "d" 127.0.0.1:6379> rpush anotherList a b c d e (INTEGER) 5 127.0.0.1:6379> ltrim AnotherList 2-2 OK 127.0.0.1:6379> lrange anotherList 0-1 1) "c" 2) "d"
#Start out of range127.0.0.1:6379> ltrim anotherList 3-1 OK 127.0.0.1:6379> lrange anotherList 0-1 (empty array)Copy the code

BLPOP

Available versions: >= 2.0.0

Time complexity: O(N), N is the number of keys provided by the command

After 6.0, the timeout argument is a double floating-point type, not an INTEGER

The command format

BLPOP key [key ...]  timeoutCopy the code

Command description

  • BLPOPIs a blocking pop-up primitive for a list
  • BLPOPLPOPThe blocking version of the command, when there are no elements in a given list to eject, will block until there are elements in the list to eject or the blocking time has expired. When multiple lists are specified, the first non-empty list element pops up in order
  1. Nonblocking behavior
  • When BPOP is called, the list is checked in order to see if it is non-empty, returning the name of the first non-empty list and the value of its header element.
  • When callingBLPOP list1 list2 list3 0If list1 is null and list2 and list3 are not null, then list2 and its header elements are returned
127.0.0.1:6379> rpush list1 hello (INTEGER) 1 127.0.0.1:6379> rpush list4 world (INTEGER) 1 127.0.0.1:6379> blpop list1 List2 list3 list4 0 1) "list1" 2) "hello" 127.0.0.1:6379> Rpush list1 hello (INTEGER) 1 127.0.0.1:6379> rpush list4 world (INTEGER) 1 127.0.0.1:6379> blpop list2 list3 list4 list1 0 1) "list4" 2) "world"Copy the code
  1. Blocking behavior
  • When a givenkeyIf both of them don’t exist, the list doesn’t exist,BLPOPWill block until another client has executedLPUSHRPUSHThe command creates the list
  • When there is a value in the list,BLPOPThe list name and the value of the element that pops up are returned
  • timeoutSpecify the blocking time,0Indicates that the blocking time can be extended indefinitely. If a non-zero parameter is specified, the blocking time is to and there is no data in the listnil
#The list does not exist, timeout=10 is specified, and nil is returned after 10s
127.0.0.1:6379> blpop notexistslist 10
(nil)
(10.06s)
Copy the code
#Client 1 calls a key that does not exist 
127.0.0.1:6379> blpop blocklist 0
1) "blocklist"
2) "name"
(48.18s)

#Start another client 2, insert data using Rpush, and the first client will return
127.0.0.1:6379> rpush blocklist name
(integer) 1
Copy the code
  1. Priority problem

The BLPOP command specifies multiple lists: from left to right, the elements of the first non-empty list are returned. Assuming that BLPOP key1, key2, key3, key4, 0, key2, and key4 are non-null, the elements in key2 will be returned

Multiple clients blocking on the same key: Returns to the earliest client among all current clients on a first-come-first-served basis

#The client 1
client1 > blpop priorlist 0

#Client 2
clietn2 > blpop priorlist 0

#The client 3
client3 > lpush priorlist lifelmy
(integer) 1

#The client 1Client1 > blPop priorList 0 1) "priorlist" 2) "lifelmy" (83.44s)Copy the code
  1. Multiple elementspushTo the list question

BLPOP returns different data in different versions when multiple elements are inserted at one time using the MULTI EXEC transaction, or when multiple elements are inserted at one time using commands like LPUSH mylist a b C.

If client A executes BLPOP and is blocked, client B executes LPUSH:

Client A:   BLPOP foo 0
Client B:   LPUSH foo a b c
Copy the code

Redis 2.4: Return a: When client B starts to insert, client A finds the data and returns it. Since the first insert is a, client A returns a

Redis 2.6 or later: Returns c: The data is not visible to the blocking client A until client B finishes executing the command. After client B executes LPUSH, c is in the header, so return C

#6.2.4 versionCliet1 > blpop foo 0 1) "foo" 2) "3" (26.31s) client2 > lpush foo 1 2 3 (INTEGER) 3Copy the code
  1. Use BLPOP in MULTI/EXEC transactions

It makes no sense to execute BLPOP in the MULTI or EXEC transaction, because the transaction will block other commands from executing LPUSH, RPUSH, etc., so that the transaction will always block BLPOP and cannot return, resulting in a deadlock. So executing a BLPOP in a transaction has the same effect as executing an LPOP; it returns without blocking

#1. When the transaction is executed, data in the list is returned directly
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> lpush mylist 1
(integer) 1
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> blpop mylist 0
QUEUED
127.0.0.1:6379(TX)> exec
1) 1) "mylist"
   2) "1"

#2. List does not exist, BLPOP in transaction returns nil directly
127.0.0.1:6379> multi
OK
127.0.0.1:6379(TX)> blpop otherlist 0
QUEUED
127.0.0.1:6379(TX)> exec
1) (nil)
Copy the code

The return value

Nil: The list has no data and times out

Array: the first element is the list name and the second is the element value

Use posture: event reminder

Sometimes, in order to wait for a new element to arrive in the data, the data needs to be probed using polling.

A better approach is to use system-provided blocking primiples that process new elements as soon as they arrive, and then block until they arrive to avoid polling resources. BLPOP solves this problem.

For example, if we want to deal with other types of data, such as Set data, which has no blocking primitive, we can use it together with a list

Consumer: Use SPOP to eject elements from set, and block to BLPOP command if no elements are present. When data arrives, BLPOP stops blocking and SPOP starts traversing the set.

LOOP forever
    WHILE SPOP(key) returns elements
        ... process elements ...
    END
    BLPOP helper_key
END
Copy the code

Producer: When data is produced, it is added to both set and list

MULTI
SADD key element
LPUSH helper_key x
EXEC
Copy the code

BRPOP

Available versions: >= 2.0.0

Time complexity: O(N), N is the number of keys provided by the command

After 6.0, the timeout argument is a double floating-point type, not an INTEGER

The command format

BRPOP key [key ...]  timeoutCopy the code

Command description

  • BRPOPIs a blocking pop-up primitive for a list
  • BLPOPRPOPThe blocking version of the command that blocks until there are no elements to eject; The list pops up at the end of the queue when it is not empty.
  • See the command descriptionBLPOP

The return value

Nil: The list has no data and times out

Array: the first element is the list name and the second is the element value

The sample

127.0.0.1:6379> flushdb OK 127.0.0.1:6379> rpush list a b c (INTEGER) 3 127.0.0.1:6379> brpop list 0Copy the code

BRPOPLPUSH

Available version: >= 2.2.0

Time complexity: O(1)

Since 6.2.0, this command has been deprecated. You are advised to use BLMOVE. See the next command

The command format

BRPOPLPUSH source destination timeout
Copy the code

Command description

  • BRPOPLPUSHRPOPLPUSHBlocking version of
  • whensourceIf there is no data in, the block will continue. When data is available, thesourceInsert table mantissa data intodestinationheader

The return value

Nil: Operation timed out

String: The element value that pops up

The sample

127.0.0.1:6379 > flushdb OK
#Client 1 is blockedClient1 > brpoplpush sourcelist destlist 0 "a" (13.87s)
#After client 2 pushes data, client 1 returns
127.0.0.1:6379> lpush sourcelist a
(integer) 1
Copy the code

Use the pose

  1. Security queue

When we pop the data from Listing 1 for processing, listing 1 will delete the data, and the data will only exist in our client. If the client suddenly goes down, the data will be lost. To prevent data loss, you can use RPOPLPUSH or BRPOPLPUSH to pop up elements and add them to another list for backup. The client will delete the elements from the backup list after processing this.

  1. Circular queue

By using the same key as both arguments of the RPOPLPUSH or BRPOPLPUSH command, the client can retrieve the list elements one after the other, eventually getting all the elements of the list, rather than having to pass all the list elements from the server to the client at once, as with the LRANGE command.

The above mode works even in two situations:

  • Multiple clients rotate the same list at the same time, fetching different elements until all have been read, and then starting from scratch.
  • There are other clients that add new elements to the end of the list.

For example, we want to achieve a monitoring alarm system, multiple servers as quickly as possible to check whether multiple websites are normal, can be multiple websites into the list, multiple servers at the same time on the list for rotation processing.

BLMOVE

Available version: >= 6.2.0

Time complexity: O(1)

Since 6.2.0, this command has been deprecated. You are advised to use BLMOVE. See the next command

The command format

BLMOVE source destination LEFT|RIGHT LEFT|RIGHT timeout
Copy the code

Command description

  • BLMOVELMOVEBlocking version of
  • whensourceWhen there is no data in, it will always block, and the rest of the operation andLMOVEconsistent

The return value

Nil: Operation timed out

String: The element value that pops up

The sample

#Client 1 is blockedClient 1> blmove sourcelist destList right left 0 "hello" (14.21s)
#After client 2 inserts data, client 1 returns data
client 2> lpush sourcelist hello
(integer) 1
Copy the code

Use the pose

See BRPOPLPUSH

More and more

Personal blog: lifelmy.github. IO /

Wechat official Account: Long Coding road