Redis common data structures and operations
Redis is an open source key-value database that supports string, list, set, zset (ordered set) and hash type data.
String
List
Set collection
Hash
Zset sorted set
String:
set/get/append/getset/setlen/del
incr/incrby/decr/decrby
setex/setnx/setrange/getrange
mget/mset/msetnx
Set data insert
set name zlh --Return value: ok, indicating that the insertion is successful. If there is a value for the current name, it will overwrite and replace the original value.
Get get data
get name --return value: "zlh" , if the current key has no value, return null
Append append data
append name is my friend --Return value: "zlh is my friend", if the value of the current key has a value, it will be appended to the original string, if not, it will be written.
redis data deletion
del name
GetSet gets the original value while writing the new value
getset name zlh --Return value: "zlh is my friend", here returns the value of the original name, and at the same time sets the new value zlh for the value of name. At this time, the value of name is the real value of zlh
get name --return value: zlh, because the value set to name by getset above is zlh.
strlen gets string length
strlen name --Return value: 3, because the value of name is zlh, so the length is 3, if the key or value does not exist, it returns 0.
incr, incrby data addition calculation
incr is +1 built-in operation, incrby is +n self-set n operation
incr name ---Return value: "The data is not an integer or the data exceeds the range of 64-bit signed integer data". Since the value of the original name is "zlh", it cannot be converted to an integer, so an exception is reported.
incr age ----Return value: 1, since there is no age key and value value, but the default age is the key value of 0 for +1 operation.
incr age ---Return value: 2, since the previous line of code assigns age to 1, the incr command here performs +1 operation, so the return value is 2.
incrby age 10 ---Return value: 12, because the original age is 2, here +10 is 12.
decr, decrby data subtraction calculation
decr is a built-in operation of -1, and decrby is a self-set n operation for subtracting n.
decr name --Return value: "The data is not an integer or the data exceeds the range of 64-bit signed integer data". Since the value of the original name is "zlh", it cannot be converted to an integer, so an exception is reported.
Decr age --Return from: 11, because the value of the original age is 12, where decr means decrement by 1, so it is 11.
decrby age 10 --Return value: 1, because the original age is 11, here -10, so it is 1.
setex sets the value and sets the expiration time (in seconds)
setex sex 20 male --- Return value: ok, set the value of key to sex is male, and the expiration time of the cache is 20s.
ddl sex ---Return value: Remaining expiration time, 0 means expired, -1 means never expires.
get sex ---Return value: male, indicating that it is not expired at this time, and the returned data is null when it has expired.
setnx Assignment judges whether the original value exists, if there is no assignment, it returns 0; if it does not exist, it assigns a value and returns 1
setnx name Tom ---Return value: 0, because the original value of name is zlh, and no value is assigned if there is a value.
get name ---Return value: zlh, because there is a value, the above assignment to tom fails and returns 0.
setnx phone 18501733702 --- Return value: 1, the assignment is successful, because the key and value of the phone do not exist originally.
get phone --- Return value: 18501733702, indicating that the above setnx assignment is successful.
setrange string replacement assignment, starting from the specified position
setrange phone 9 123 -- Return value: 12, 12 is the length of the string, and the 11-digit number has become 12. Because the replacement starts from the 9th digit, the replacement to the last digit of the original string has not been completed, so the last digit is added and set to 3.
get phone --- The return value is: 185017337123.
set phone 1 --- Here, in order to talk about other features of setrange below, set the phone to 1.
setrange phone 3 aaa ---The return value is: 6, because the value of the original phone is 1, less than three digits, and 2 digits are replaced with 0*00, so it is necessary to add 2 to replace the value after the third digit aaa.
get phone --- Return value: 1\*00\*00aaa. Understand the above operation to know why this return value is here.
getrange intercepts the string, starting from the subscript n to n or n+1, similar to substring in c#
set phone 18501733701
getrange phone 1 5 ---Return value: 85017, because getrange is intercepted from subscript 1 to subscript 5, which contains the value of subscript 5.
getrange phone 0 0 --- Return value: 1, intercepted from subscript 0, intercepted to subscript 0, including subscript 0. So the return value is 1.
getrange phone 10 13 -- The return value is: 1, the 11-digit number with the subscript of this number up to 10, intercepted from 10 to the 13th digit, the last 2 digits are ignored, and only the 10th digit is returned. So it returns a clean 1.
Batch operation to modify and read string data
mget batch read, mset batch assignment, msetnx with transactional assignment , found that a key already exists, all transactions return, no assignment processing operation
mset name zlh age 30 --- Return value: ok, where the key is set to name and the value of age is zlh, 30
mget name zlh --- return value: 1>zlh 2>30
msetnx name Jim address China ---The return value is: 0, no modification is made, because the key already exists
mget name address --- Return value: 1>zlh 2>null
msetnx address China,hobbies sports --The return value is: 1, the insertion is successful
mget address hobbies --- Return value: 1>China 2>sports
List list
1. What are the basic attributes of list in redis?
The List data structure is a linked list structure , which means that regardless of the amount of data, the head and tail operations are still very fast. The capacity of the list is 2 to the 32nd power minus 1 element, that is, 4294967295 elements.
2. Why use the list data type in redis?
Relying on the advantages of operating data in the memory of redis, it also provides a series of practical and unique APIs to manipulate data, which is easy to use, fast, and can achieve unique data features sorting, reading and writing, timeline data, comment list, message delivery, etc. And so on, but also provides simple paging, read and write operations. Do you need it.
3. Why use message queue?
For a simple example, the function is like this. You want to present the page to the user. Before you present the page, there is a very complicated and time-consuming operation to operate, but this operation does not affect the data presented by the page, nor is it used as a page. rendered data.
Option 1: After the operation is completed, the page is rendered.
Option 2: Throw the data to be calculated into the persistent message queue, and directly render the page without doing time-consuming operations. Then use another program to perform operations on the data in the message queue separately.
Obviously, the second solution is the best answer, do you use message queues or not.
4. Why not use the mature rabbitmq and use the message queue implemented by redis?
Rabbitmq only pays attention to the first-in, first-out of data, and there is no concept of data priority. If you want to give that data a privilege to process first, then sorry, I don't support it, but rabbitmq can also handle it in a flexible way, that is, to create multiple Queues use program routing to implement this privileged function. Then the message queue implemented by redis can be flexibly controlled, which will be demonstrated later.
Redis implements message queue and comes with its own priority function
1. First of all, the list in redis is a linked list structure, which has the first-in-first-out feature in the message queue.
2. As can be seen from the above advanced commands, list has several built-in blocking functions, and the time is set to 0, which can be regarded as a monitoring process that never rests.
lpush/rpush/lpop/rpop
lrange / llen / lindex
lpush, rpush, linsert data insertion commands:
rpush inserts data into the mylist list from the right
rpush mylist 1 --- result is: (integer) 1
rpush mylist 2 --- the result is: (integer) 2
rpush mylist 3 --- result is: (integer) 3
lrange mylist 0 -1 ---lrange command: View the data in the mylist list, 0 starts at position, -1 ends at -1, when the end position is -1, it means the last position in the list, that is, view all. The result is: 1> "1" 2> "2" 3> "3"
lpush mylist 0 ---lpush command: insert a piece of data with 0 data from the left into the mylist list
lrange mylist 0 -1 ---结果为:1>"0" 2>"1" 3>"2" 4>"3"
linsert mylist after 3 4 ---linsert command, the expression is linsert key before|after pivot value; this command means to find the data with the value of 3 in the list whose key is mylist, and insert a value of 4 after it The data.
lrange mylist 0 -1 ---结果为:1>"0" 2>"1" 3>"2" 4>"3" 5>"4"
linsert mylist before 0 -1 --- means: find data with a value of 0 in the list whose key is mylist, and insert a piece of data with a value of -1 before it.
lrange mylist 0 -1 ---结果为:1>"-1" 2>"0" 3>"1" 4>"2" 5>"3" 6>"4"
lisert mylist after 5 8 --- The result is: -1, since there is no data with a value of 5 in the mylist list, no operation is performed, and the status value -1 is returned. If the key does not exist, an error message is returned.
lrange mylist 0 -1 ---结果为:1>"-1" 2>"0" 3>"1" 4>"2" 5>"3" 6>"4"
Delete data: lpop, rpop
lpop mylist ---lpop command: remove a piece of data from the left side of the list, and output the deleted data at the same time, the output result here is -1
lrange mylist 0 -1 ---结果为:1>"0" 2>"1" 3>"2" 4>"3" 5>"4"
rpop mylist ---rpop command: remove a piece of data from the right side of the list, and output the deleted data at the same time, the output result here is 4
lrange mylist 0 -1 ---结果为:1>"0" 2>"1" 3>"2" 4>"3"
ltrim mylist 1 3 ----ltrim command: keep the values of the two subscript intervals set, and delete all values that are not in the interval. 1 is the subscript value reserved at the beginning, and 3 is the subscript value reserved at the end.
lrange mylist 0 -1 --- the result is: 1>"1" 2>"2" 3>"3"
View data: lrange, llen, lindex
llen mylist ---llen command: return the length of the list, where there are only 4 pieces of data left in mylist, so the output result is 4
lindex mylist 3 ---lindex command: Get the data at a given location, where the data with the coordinate 3 is "2", so the result is 2.
Modify data: lset
lset mylist 2 zlh ---lset command: set the value of subscript 2 to zlh, if the subscript value is out of range or perform lset on an empty list, an error message will be returned
lrange mylist 0 -1 ---The result is: 1>"1" 2>"2" 3>"zlh"
Two lists A, B, add the tail element of the A list to the head element of the B list, command: rpoplpush
#Here I have a list A with {1,2,3} data and B list data {4,5,6}
rpoplpush A B
lrange A --- the result is: 1>"1' 2>"2"
lrange B ---结果为:1>"3' 2>"4" 3>"5" 4>"6"
Several advanced commands with blocking: blpop, brpop, brpoplpush
blpop A 30 --- means: if the A list has a value, remove a data from the left, if there is no value, wait until the data is inserted in A, the waiting time is 30 seconds, if the time is set to 0, the blocking time is infinite extend
blpop B30 --- means: if there is a value in the A list, remove a data from the left, if there is no value, wait until the data is inserted in A, the waiting time is 30 seconds, if the time is set to 0, the blocking time is infinitely extended
brpoplpush AB 30 --- means: add the tail element of the A list to the head element of the B list, if there is a value in the A list, insert it, if there is no value, wait until the data is inserted in A, and the waiting time is 30 seconds , if the time is set to 0, the blocking time will be extended indefinitely
Set
Set uses a hash table to maintain the uniqueness of strings. There is no sequence. Unlike list, data can be added or deleted at the beginning and end.
sadd/smembers/sismember/srem/
scard/srandmember/spop/smove/sinter
Commands that operate on a single set
Sadd adds new data, the value value under the same key value cannot be repeated, returns the number of inserted data, and the key can be followed by multiple value values
sadd mySet 1 --- add the set data value whose key is mySet is 1,
sadd mySet 2 4 5 ---Add the set data value whose key is mySet is 2,
smembers View the set data set data , you can get all the elements
smembers mySet --- Get the set data value set whose key is mySet
sismember judges whether there is a certain value in the value of a key , if it exists, it returns 1, if it does not exist, it returns 0
sismember mySet 3 --- The return value is 0, because there is only 1 in the set member of myset, 2 does not have 3
sismember mySet 2 --- The return value is 1, because 2 exists in the Set member of myset.
srem deletes data, returns the number of deletions , the key can be followed by multiple value values
srem mySet 1 --- delete the data item whose key is mySet and whose value is 1.
srem mySet 2 4 --- delete 2 data items with key mySet and value 2 and 4.
scard Check the number of set data , if it does not exist, return 0
sadd mySet 1 2 3 4 5
scrad mySet --- Check how many data items exist in mySet, the return result is 5
srandmember randomly view elements
srandmember mySet --- output a random value in the data item whose key is mySet,
spop removes an element at random and returns the removed data
spop mySet ---- randomly delete a piece of data from the data set whose key is mySet, and return the deleted data
scard mySet --- The number of data in the data set whose key is mySet is 4
Commands for manipulating multiple sets
In addition to adding, deleting, modifying and checking elements in a set, a set can also operate on multiple sets, such as moving the elements of one set to another set, and calculating the union, intersection, and difference of multiple sets. .
smove moves elements from one set to another set
sadd mySet 1 2 3 ----Add 3 pieces of data to mySet 1 2 3
sadd youSet 3 4 5 ---- add 3 pieces of data to youSet 3 4 5
smove youSet mySet 4 --- remove data 4 in youSet and add data 4 to mySet
smembers mySet --- Result is: 1 2 3 4
smembers youSet --- result is 3 5
sinter find intersection
sinter mySet youSet --- The output result is the intersection of mySet and youSet, and the output result is: 3
sunion union
sunion mySet youSet --- The output result is the union of mySet and youSet, the output result is: 1 2 3 4 5
sdiff difference set
sdiff mySet youSet --- The output result is the data that does not exist in youSet in mySet, the output result is: 1 2 4
sdiff youSet mySet --- The output result is the data that does not exist in mySet in youSet, and the output result is: 5
Hash:
The array is quickly located to the specified element by index. Whether it is to access the first element or the last element of the array, the time spent is the same, but the index in the array has no practical significance, it is just a position. When we look for an element, we generally use meaningful fields as indexes, which results in a dictionary. In fact, the implementation of dictionary is to make the key have a certain relationship with the subscript index.
hash is a mapping table of field and value of string type, hash is especially suitable for storing objects .
hset key field value can understand that the key is the object name field is the attribute value is the attribute value
hget key field Get the value of the field of the specified key
hmset key field1 value1 field2 value2 Set multiple fields and their values for the specified key
hmget key field1 field2 Get the value of field1 and field2 of the specified key
hkeys key Get all fields of the specified key
hvals key Get the value of all fields of the specified key
hdel key field1 [field2] delete one or more fields of the specified key
hexists key field Check whether the field of the specified key exists, if it exists, it returns 1, if it does not exist, it returns 0
hgetall key returns all fields and field values for the specified key.
hlen key returns the number of fields with the specified key
of the key
hset/hsetnx/hget/hdel
Add the command hset, if the key does not exist, create the key, if it exists, overwrite the original value
hset myhash name Jim ---- Set the key value of myset to the name value of Jim
View the command hget
hget myhash name ---- output: "Jim", get the value whose key is myset and whose key is name
hset myhash name zlh ---- overwrite the original value, change the value to zlh to replace Jim
hget myhash name --- output: "zlh"
The command hlen to get the number of fields contained in the key
hset myhash age 31 --- set key to value=31 of myset key to age
hlen myhash --- the output is 2, and the number of fields whose key is myset is 2
The command hexists to determine whether the specified field in the specified key exists , returns 1 if it exists, and returns 0 if it does not exist
hexists myhash name --- returns 1, indicating existence
hexists myhash name1 --- returns 0, indicating that it does not exist
delete command hdel , delete one or more specified fields
hset myhash sex nan ---- add data
hset myhash issingle yes ---- add data
hset myhash hobby sports ---- add data
hdel myhash hobby ---- delete a single data, filed is the data of hobby
hdel myhash issingle sex --- delete multiple data, filed is two data of issingle and sex
If the key or field does not exist, the insert is valid, otherwise no action is taken by the command hsetnx
hsetnx myhash sex nan --- Set myhash, the value of field as sex is nan, and successfully returns 1, because the field of sex does not exist
hsetnx myhash sex nv --- set myhash, the value of field as sex is nv, if unsuccessful, return 0, because the field of sex originally exists and has a value
hget myhash sex -- output "nan"
The command hincrby to operate the increase and decrease
del myhash --- delete the key
hset myhash age 31 --- set the key of myhash to the age value of 31
hincrby myhash age 10 --- Add 10 to the value of key myhash and age, and the output result is 41
hincrby myhash age -10 --- Give the key as myhash, subtract 10 from the value of the key as age, and the output result is 31