Key pattern Query the corresponding key

(1) Redis allows fuzzy query key to have 3 wildcards *,? And []

(2) randomkey: returns a randomkey

(3) Type Key: Returns the type of the key storage

(4) Exists key: checks whether a key exists

(5) del key: deletes the key

(6) rename key newkey: Rename a key

(7) renamenx key newkey: If the newkey does not exist, the change is successful

(8) Move key 1: Move key to 1 database

TTL key: query key life cycle (seconds)

(10) Expire key integer value: Set the lifetime of the key in seconds

(11) PEXPIRE key integer value: Sets the lifetime of the key in milliseconds

(12) PTTL key: query key life cycle (ms)

(13) Perisist key: Sets the specified key to be permanent

String operations

(1) set key value [ex seconds] [px milliseconds] [nx/xx]

If ex and px are written at the same time, the subsequent validity period prevails

Nx: establishes the key if it does not exist

Xx: If the key exists, change its value

(2) Get key: specifies the value

(3) mset key1 value1 key2 value2 Sets multiple values at a time

(4) mget key1 key2: get multiple values at once

(5) setrange key offset value: changes the offset byte of the string to value

If offset > string length, the character is automatically supplemented with 0x00

(6) Append key value: Appends value to the original key value

(7) getrange key start stop: obtains the value in the range of [start, stop] in the string

For subscripts of strings, the left digit starts at 0 and the right digit starts at -1

Note: When start>length, an empty string is returned

When stop>=length, the string is truncated to the end

If start is to the right of stop, an empty string is returned

(8) getSet key nreValue: Gets and returns the old value, and sets the new value

(9) incr key: increment, return new value, if incr a value that is not an int, return error, incr a key that does not exist, set key to 1

(10) Incrby key 2: jump 2 increases automatically

(11) IncrByFloat by 0.7: auto-increment floating point number

(12) setbit key offset value: Sets the binary value of offset and returns the old value of this bit

Note: If offset is too large, zeros are filled in between

What is the maximum value of offset

2^32-1, the largest string is 512MB

(13) Bitop operation destkey key1 [key2.. Perform opecation on key1 key2 and save the result on destkey

Opecation can be AND OR NOT XOR

Strlen key: takes the length of the value of the specified key

(15) setex key time value: Set the value of the key and set the validity period to time seconds

3. Linked list operation

The Redis list is essentially a bidirectional list where each child element is a string, and the maximum length of the list is 2^32. Lists can be used as either stacks or queues.

Pop operations on list also block versions, mainly to avoid polling

(1) lpush key value: insert the value into the linked list header

(2) rpush key value: insert the value to the end of the list

(3) LPOP key: return and delete the linked list header element

(4) RPOP key: return and delete the end of the list element

(5) lrange key start stop: return elements in the linked list [start, stop]

(6) LREM key count value: Delete the value value from the linked list. End after deleting the absolute value of count

Count > 0 Delete from table header count < 0 delete from table tail count=0 delete from table header

(7) ltrim key start stop: cut the link corresponding to the key, cut the segment [start, stop] and assign the change to the key

Lindex key index: returns the value of the index

(9) llen key: Calculate the number of linked list elements

(10) linsert key after | before the search value: the key chain in the table to find the search, and insert the value before | after the search value

(11) rpoplpoplpush the end of source dest to the end of dest

Application scenario: The task + BAK double-linked list completes the security queue

    

Business logic: rpoplpush Task bak

Receive the return value and do business

If successful, rPOP bak clears the task. If not, the task is fetched from the BAK table next time

(12) BRPOP, blPOP key timeout: wait for the end/head element of the key to pop

Timeout indicates the waiting timeout period. If timeout is 0, the waiting period continues

Application scenario: Long ajax polling, used in online chat

Iv. Hashes type and operation

Redis hash is a mapping of fields and values of string type, and its add and remove operations are O(1) (average). Hash is especially suitable for storing objects. Storing an object in the hash type consumes less memory and allows easy access to the entire object.

Configuration: hash_max_zipmap_entries 64 # Configuration field maximum 64

Hash_max_zipmap_value 512 # Set value to a maximum of 512 bytes

(1) hset MyHash field value: Sets the field of myhash to value

(2) hsetNx myHash Field value: Sets the field of myhash to value if it does not exist

(3) hmset myHash field1 value1 field2 value2: Set multiple fields at the same time

(4) hget myHash Field: Obtains the specified hash field

(5) hmget myHash field1 field2: fetch multiple fields at once

(6) hincrby myHash Field 5: Specifies the hash field plus the given value

(7) hexists myHash field: tests whether the specified field exists

(8) hlen myHash: Returns the number of hash fields

(9) hdel myHash Field: Deletes the specified field

(10) hkeys myHash: Returns the hash of all fields

(11) hVALS myhash: Returns all hash values

(12) hgetall myHash: Obtains all fields and values of a hash

5. Set structure operation

Characteristics: disorder, certainty, uniqueness

(1) sadd key value1 value2: Adds elements to the set

(2) smembers key: retrieves all elements of the set

(3) sREM key value: delete an element of the set

(4) Spop key: return and delete 1 random element in the set (can sit in the lottery, won’t pick someone again)

(5) SrandMember key: randomly select an element

(6) sismember Key Value: Determine whether the set has a certain value

(7) SCard key: returns the number of set elements

(8) smove source dest value: Move the value of the source to dest

Sinter key1 key2 key3: find the intersection of key1 key2 key3

(10) sunion key1 key2: find the union of key1 key2

(11) sdiff key1 key2: find the difference of key1 key2

(12) sinterstore res key1 key2: Find the intersection of key1 key2 and store it in res

Ordered set

Concept: It adds an order attribute to set. This attribute can be specified when adding modified elements. After each attribute is specified, ZSet automatically adjusts the order according to the new value. Mysql > select * from zset; select * from zset; select * from zset; select * from zset; select * from zset;

Just like sets, sorted, sets are collections of string elements, except that each element is associated with a double score. The sorted set implementation is a mix of skip List and Hash table.

When an element is added to the collection, an element’s mapping to score 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 retrieved in order. The overhead of add and delete operations is the same as that of SKIP List. The skip List implementation of Redis is a bidirectional linked list, so elements can be removed from the tail in reverse order. The sorted set is most often used as an index. We can store the sorted fields as scores and the ids of objects as elements.

(1) zadd key score1 Value1: adds elements

(2) Zrange key start stop [withscore] : after sorting the set, the elements returning the rank [start,stop] are arranged in ascending order by default. Withscores is also printed out

(3) zrank key member: select member from ‘0’;

(4) ZrangebyScore key min Max [withscores] limit offset N: after sorting the set (ascending), take the elements within score of [min, Max], skip the offset and take out N

(5) zrevrank key member: select member from zrevrank;

(6) ZremrangebyScore key min Max: deletes elements according to score, and deletes score between [min, Max]

(7) zrem key value1 value2: deletes elements in the set

(8) zremrangebyrank key start end: delete elements in the order of [start, end]

(9) Zcard key: Returns the number of set elements

Zcount key min Max: returns the number of elements in the interval [min, Max]

(11) ZinterStore Dest NumKeys key1[key2..] [WEIGHTS weight1 [weight2…]] [AGGREGATE SUM|MIN|MAX]

Weight1; weight2; key1; weight2

The polymerization method with sum | min | Max

The result of the aggregation is saved in the sub-dest collection

Weights and aggregate

A: If there is an intersection, and the intersection element has score, how to deal with score? Aggregate num->score, min minimum score, Max maximum score, in addition, the weights of different keys can be set through weights, score*weight when the intersection

Server-related commands

(1) Ping: Determine whether the connection is alive

(2) Echo: Prints some content on the command line

(3) select the database

(4) quit: Exits the connection

Dbsize: returns the number of keys in the current database

(6) info: Obtains server information and statistics

(7) Monitor: dumps received requests in real time

(8) config get Configuration item: Obtain server configuration information

Config set Configuration item value: Configures the configuration item information

(9) flushdb: deletes all keys in the current selected database

Flushall: deletes all keys from all databases

(11) time: displays the server time, timestamp (s) and microseconds

(12) bgreWRITEAOF: Saves RDB snapshots in the background

(13) BGSave: RDB snapshot saved in the background

(14) save: Saves the RDB snapshot

(15) LastSave: last saved time

(16) Shutdown [save/nosave]

Note: if you accidentally run flushall, shutdown the nosave immediately, then manually edit the aof file to remove the flushall-related lines from the file, and then start the server to rewind the original data. If the system happens to be bgWriteAof after flushall, the aOF is flushed and the data is lost.

(17) showlog: displays slow queries

Q: How slow is slow?

Answer: Slowlog-log-slower than 10000 (in microseconds)

Q: How many slow query records does the server store

Slowlog-max-len 128 is used to limit slowlog-max-len 128

Other references:

Redis command reference