In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "Redis commonly used operation commands", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor to take you to learn the "Redis common operation commands" it!
1. Key pattern queries the corresponding key
(1) redis allows fuzzy query of key
The keys command has three wildcards *,?, [], and an escape
? Match a character
* match any (including 0) characters
[] to match any character between parentheses, you can use the "-" symbol to indicate a range, such as "ab", "ac", "ad".
\ x matches the character x, which is used to escape symbols, if you want to match "?" You need to use\?
(2) randomkey: returns random key
(3) type key: returns the type of key storage
The return value may be string (string type), hash (hash type), list (list type), set (collection type), zset (ordered collection type)
(4) exists key: determine whether a key exists [if so, return integer type 1, otherwise return 0]
(5) del key: delete key
Del key [key.]
You can delete one or more keys, and the return value is the number of keys deleted.
Note: wildcard deletion is not supported
(6) rename key newkey: rename
(7) renamenx key newkey: modified successfully if newkey does not exist
(8) move key 1: move key to database 1
(9) ttl key: query the lifecycle of key (seconds)
(10) expire key integer value: sets the life cycle of key in seconds
(11) pexpire key integer value: sets the life cycle of key in milliseconds
(12) pttl key: query the lifecycle of key (milliseconds)
(13) perisist key: sets the specified key to be permanent
Second, string type operation
(1) set key value [ex seconds] [px milliseconds] [nx/xx]
If ex and px are written at the same time, the later validity period shall prevail.
Nx: set up if key does not exist
Xx: modify the value of key if it exists
(2) get key: value
(3) mset key1 value1 key2 value2 sets multiple values at a time
(4) mget key1 key2: get multiple values at a time
(5) setrange key offset value: change the offset offset byte of a string to value
If offset > string length, the character automatically complements 0x00
(6) append key value: append value to the original value of key and add value to the tail
The function is to append value to the end of the key value, and if the key does not exist, set the key value to value, which is equivalent to set key value.
The returned value is the length of the appended string, such as: append foo "hello word!"
(7) getrange key start stop: get the value in the range of [start, stop] in the string
For the subscript of a string, the left number starts at 0 and the right number starts at-1
Note: when start > length, an empty string is returned
When stop > = length, truncate to the end of the string
If the start is to the right of the stop, an empty string is returned
(8) getset key nrevalue: get and return the old value, and set the new value
(9) incr key: self-increment, return a new value. If incr is a value that is not int, an error is returned. If incr is a key that does not exist, set key to 1.
Incr key when the stored string is in the form of an integer, redis provides a command to use incr to increment the current key value
And return the incremented value
Incr num defaults to 0 when the key to be operated does not exist, so the result after the first increment is 1
Redis prompts an error when the key value is not an integer
(10) incrby key increment: increase the specified integer [incrby key 2: jump 2 increment]
The incrby command is basically the same as the incr command, except that the former can specify a numerical increase at a time through the increment parameter
For example: incrby num 2 incrby num 3
(11) incrbyfloat by 0.7: self-increasing floating point Note: (due to the limitation of reids version, the version needs to be greater than 2.6)
(12) reduce the specified integer
Decr key
Decrby key increment
The desc command uses the same as the incr command, except that the key value is decremented.
The decrby command is used the same as the incrby command
Bit operation: a byte consists of 8 binary bits. Redis provides 4 commands to operate on binary bits directly.
(13) setbit key offset value: set offset to correspond to the value on the binary, and return the old value on this bit
[note: if the offset is too large, 0 will be filled in the middle.
What is the maximum offset? 2 ^ 32-1, and the maximum string is 512m]
The setbit command sets the value of the binary bit of the position specified by the string type key, and the return value is the old value of that position.
If the position to be set exceeds the length of the binary bit of the key value, the setbit command automatically sets the middle binary bit to 0
Similarly, setting the value of the specified binary bit of a non-existent key automatically assigns the bit in front of it to 0
14) getbit key offset value:
The getbit command can get the value (0 or 1) of the binary bit at the specified position of a string type key, with the index starting at 0
If the index of the binary bit to be obtained exceeds the actual length of the binary bit of the key value, the default bit value is 0
(15) bitcount key [strart] [end]
The bitcount command can get the number of binary bits with a value of 1 in the string type key, and the byte range of statistics can be limited by parameters.
If we want to count the first two bytes (that is, "aa") command: bitcount foo 0 1
Note: (due to the limitation of reids version, the version needs to be greater than 2.6)
(16) bitop operation destkey key1 [key2..] Opecation key1 key2 and save the results on destkey
[opecation can be AND OR NOT XOR]
The bittop command can perform bit operations on multiple string type keys and store the results in the key specified by the destkey parameter.
The operations supported by this command are AND, OR, XOR, and NOT
For example, we perform OR operations on bar and aar:
Set foo1 bar
Set foo2 aar
Bitop OR res foo1 foo2
Get res
Note: (due to the limitation of reids version, the version needs to be greater than 2.6)
(17) strlen key: take the length of the value of the specified key [return the length of the key value, or 0 if the key does not exist]
(18) setex key time value: set the value value corresponding to key, and set the validity period to time seconds
III. Linked list operation
The list type of Redis is actually a two-way linked list with each child element of type string. The maximum length of the linked list is 2 ^ 32. List can be used as either a stack or a queue.
There is also a blocking version of list's pop operation, mainly to avoid polling
(1) add elements to both ends of the list
Lpush key value [value. ]
Rpush key value [value. ]
The lpush command is used to add an element to the left of the list, and returns the length of the list after adding the element.
The rpush command is used to add elements to the right of the list, and returns the length of the list after adding elements.
(2) Pop elements from both ends of the list
Lpop key
Rpop key
The lpop command pops up an element from the left side of the list, and the lpop command performs two steps
1: remove the element on the left of the list from the list
2: returns the value of the removed element
The rpop command pops up an element from the right side of the list
(3) llen key: calculate the number of elements in the linked list [llen returns 0 when the key does not exist]
(4) lrange key start stop: returns the elements in [start, stop] in the linked list
Get a fragment of the list and return that the index starts with 0 for all elements (including elements at both ends) from start to stop
Note: one difference between lrange and the method used to intercept array fragments in many languages is that the value returned by lrange contains the rightmost element
The lrange command also supports negative indexes, and the table calculates the ordinal from the right.
For example,'- 1 'represents the first element on the right, and'-2 'represents the second element on the right, and so on.
(5) lrem key count value: delete the value from the linked list, delete the absolute value of count and end with value
Count > 0 removes count from the header
< 0 从表尾删除 count=0 全部删除 lrem 命令会删除列表中前 count 个值为 value 的元素,返回值是实际删除的元素个数。 根据count 值的不同,lrem 命令执行的方式会略有差异 当 count >At 0, the lrem command deletes the elements whose previous count value is value, starting from the left of the list
When count
< 0 时,lrem 命令会从列表右边开始删除前count 个值为 value 的元素 当 count = 0 时,lrem 命令会删除所有值为value的元素 (6)lindex key index:返回index索引上的值 lindex 命令用来返回指定索引的元素,索引从 0 开始 ,如果 index 是负数则表示从右边开始计算的索引, 最右边元素的索引是 -1 (7)lset key index value:设置index索引上的值 lset 是通过索引操作列表的命令,它会将索引为 index 的元素赋值为 value (8)ltrim key start stop:只保留列表指定片段,剪切key对应的链接,切[start, stop]一段并把该值重新赋给key, ltrim 命令可以删除指定索引范围之外的所有元素,其指定列表范围的方法和 lrange 命令相同 ltrim 命令常和 lpush 命令一起使用来限制列表中元素的数量, 比如记录日志时我们希望只保留最近的 100 条日志,则每次加入新元素时调用一次ltrim 命令即可; (9)linsert key after | before search value:向列表中插入元素, 在key 链表中寻找search,并在search值之前|之后插入value linsert 命令首先会在列表中从左到右查找值为 search 的元素, 然后根据第二个参数是 before 还是 after 来决定将 value 插入到该元素的前面还是后面,如果命令执行成功, 返回插入操作完成之后列表的长度。如果没有找到 search 返回 -1 如果key 不存在或为空,返回 0 (10)rpoplpush source destination:将元素从一个列表转到另一个列表R 把source 的末尾拿出,放到destination头部,并返回单元值 应用场景: task + bak 双链表完成安全队列Business logic: rpoplpush task bak
Receive the return value and do business processing
If successful, rpop bak clears the task; if not, next time fetch the task from the bak table
Rpoplpush executes the rpop command before the lpush command. The rpoplpush command first pops up an element from the right side of the source list type key
Then add it to the left of the destination list type key and return the value of this element. The whole process is atomic.
(11) brpop,blpop key timeout: wait for the tail / header element of the key to pop up
Timeout is the timeout for waiting. If timeout is 0, you will wait forever.
Application scenario: long polling ajax, which can be used when chatting online
Type and operation of hashes
Redis hash is a mapping table of field and value of type string, and its add and delete operations are both O (1) (average). Hash is especially suitable for storing objects. Storing an object in a hash type takes up less memory and can easily access the entire object.
Configuration: up to 64 hash_max_zipmap_entries 64 # configuration fields
Hash_max_zipmap_value 512 # configure value with a maximum of 512 bytes
(1) hset key field value is used to assign values to fields.
[hset myhash field value: set the field of myhash to value]
The convenience of the hset command is that it does not distinguish between insert and update operations, which means that you do not have to determine whether the field is saved in advance when modifying the data
When deciding whether to perform an insert operation or an update operation, the hset command returns 1 when the insert operation is performed
When an update operation is performed, the hset command returns 0, and when the key itself does not exist, the hset command automatically establishes it.
(2) hmset key field value field value. ] set multiple key values
[hmset myhash field1 value1 field2 value2: set multiple field at the same time]
(3) the hget key field command is used to obtain the value of the field.
[hget myhash field: get the specified hash field]
4) hmget key field [field. ] get multiple key values
[hmget myhash field1 field2: get more than one field at a time]
(5) hgetall key: used when getting all the fields and field values in the key but not knowing which fields are in the key. The returned result is a list of fields and field values.
[hgetall myhash: get all the field and value in a hash]
(6) hsetnx key field value: assign a value when a field does not exist
[hsetnx myhash field value: set the field of myhash to value if it does not exist]
The hsetnx command is similar to the hset command, except that the hsetnx command does nothing if the field already exists.
(7) hexists key field determines whether the field exists [return 1 if it exists, otherwise return 0]
[hexists myhash field: test whether the specified field exists]
(8) hincrby key field increment increases the field value by a specified integer
[hincrby myhash field 5: specified hash field plus given value]
(9) number of fields obtained by hlen key [hlen myhash: number of field returned by hash]
(10) hdel key field [field.] Delete one or more fields, and the return value is the number of fields deleted.
[hdel myhash field: delete the specified field]
(11) hkeys key gets the names of all fields [hkeys myhash: returns all field of hash]
(12) hvals key gets the values of all fields in the key [hvals myhash: returns all value of hash]
Collection structure operation
Characteristics: disorder, certainty and uniqueness
(1) sadd key member [member.... ]: add elements to the collection
The sadd command is used to add one or more elements to the collection and is automatically created if the key does not exist.
Because there cannot be the same element in a collection, it will be ignored if the element you want to add already exists in the collection.
The return value is the number of elements successfully added (ignored elements are not counted)
(2) srem key member [member.... ]: delete an element of the collection
The srem command is used to delete one or more elements from the collection and returns the number of successful deletions.
(3) smembers key: get all the elements of the collection
(4) spop key: returns and deletes a random element in the collection (can draw a lottery without repeatedly drawing someone)
Because the elements of the collection type are unordered, the spop command pops up by randomly selecting an element from the collection
The return value is the random element that has been removed. If key does not exist or key is empty, nil will be returned.
(5) sismember key value: determine whether the set has a certain value
Determining whether an element is in a collection is an operation with a time complexity of 0 (1).
No matter how many elements there are in the collection, the sismember command always returns results very quickly.
The sismember command returns 1 when the value exists and 0 if the value does not exist or the key does not exist
(6) scard key: returns the number of elements in the collection
(7) smove source dest value: move the value of source to the dest collection
(8) srandmember key [count] randomly gets the elements in the set.
This command is used to randomly get an element from the collection
You can also pass the count parameter to get multiple elements randomly at one time, and the specific performance is different according to the positive or negative of count.
When count is positive, srandmember randomly fetches count non-repeating elements from the collection.
If the value of count is greater than the number of elements in the collection, srandmember returns all elements in the collection
When count is negative, srandmember randomly gets count elements from the collection, which may be the same.
[note: prompt command parameter error in windows environment when passing count parameter]
Inter-set operation
9) sdiff key [key. ] [sdiff key1 key2: find the difference of key1 key2]
The sdiff command is used to perform subtraction operations on multiple sets. The difference between set An and set B is expressed as A-B.
Represents a collection of all elements belonging to An and not belonging to B, that is, A-B = {x | x ∈ An and x ∈ / B}
How to use the command:
Sadd seta 1 2 3 4 6 7 8
Sadd setb 2 3 4
Sdiff seta setb
This command allows multiple keys to be passed in at the same time. The order of calculation is to calculate the difference between seta and setb in the calculation result and setc.
Sadd setc 2 3 4
Sdiff seta setb setc
(10) sinter key [key. ] [sinter key1 key2 key3: find the intersection of key1 key2 key3]
This command is used to perform intersection operations on multiple sets. The intersection of set An and set B is represented by A ∩ B.
Represents a collection of all elements belonging to An and B, that is, A ∩ B = {x | x ∈ An and x ∈ B}
How to use the command:
Sinter seta setb
This command also supports passing in multiple keys at the same time
(11) sunion key [key. [sunion key1 key2: find the union of key1 key2]
This command is used to perform union operations on multiple sets. The union of set An and set B is represented by A ∪ B.
Represents a collection of all elements belonging to An or B, that is, A ∪ B = {x | x ∈ An or x ∈ B}
How to use the command:
Sunion seta setb
This command also supports passing in multiple keys at the same time
Perform set operations and store the results
(12) sdiffstore destination key [key. ]
The sdiffstore command has the same function as the sdiff command, except that the former does not directly return the result of the operation.
Instead, the result is stored in the destination key.
(13) sinterstore destination key [key. [sinterstore res key1 key2: find the intersection of key1 key2 and store it in res]
The command sinterstore is similar to the sinter command
But it saves the results to the destination collection instead of simply returning the result set
(14) sunionstore destination key [key. ]
The command sunionstore is similar to the sunion command
But it saves the results to the destination collection instead of simply returning the result set.
VI. Orderly collection
Concept: it adds a sequence attribute to set, which can be specified when adding modified elements, and after each assignment, zset automatically adjusts the order according to the new value. It can be understood as a mysql table with two columns, one column storing value and one column storing order, and key is understood as the name of zset in the operation.
Like set, sorted,sets is also a collection of elements of type string, except that each element is associated with a score of type score. The implementation of sorted set is a mixture of skip list and hash table.
When an element is added to the collection, an element-to-score mapping is added to the hash table, so the cost of getting score for a given element is O (1). Another score-to-element mapping is added to the skip list and sorted by score, so the elements in the collection can be fetched sequentially. The cost of adding and deleting operations is the same as that of skip list (logN). The skip list implementation of redis is a bi-directional linked list so that elements can be removed from the tail in reverse order. The most common way to use sorted set is to use it as an index. We can store the fields to be sorted as score and the ID of the object as elements.
1. Zadd key score member [score member. ]: add elements
The zadd command is used to add an element and its score to an ordered collection.
If the element already exists, the original score is replaced with the new score. The return value of the zadd command is the number of elements newly added to the collection
(does not contain elements that already exist)
Get a list of elements ranked in a certain range
(2) zrange key start stop [withscore]: after sorting the collection, return the element of rank [start,stop]
The default is to ascend withscores and print out the score.
The zrange command returns all elements indexed from start to stop in the order of element scores.
(contains elements at both ends). The zrange command is very similar to the lrange command, for example, the index starts at 0
A negative number means to look from back to front (- 1 represents the last element).
If you need to score an element at the same time, you can add the widthscores parameter to the end of the zrange command.
Note: if the scores of the two elements are the same, redis will follow the dictionary order (i.e. 0
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.