[redis] redis common commands

Time:2021-2-3

IP:192.168.225.128
Environment: centos7

1、 Global command
1. Query key
Keys * queries all the keys, traverses all the key values, complexity O (n)

2. Total number of keys
Dbsize queries the total number of keys and directly obtains the built-in variable of the total number of keys in redis. The complexity is O (1)

3. Check whether the key exists
The exists key returns 1 if it exists and 0 if it does not exist

4. Delete key o (k)
Del key [key…] returns the number of keys successfully deleted

5. Key expiration
When the expiration time exceeds, the key will be automatically deleted, and the key will expire in seconds
The expire key timestamp key expires after the second level timestamp
When the expiration time of pexpire key milliseconds exceeds, it will be automatically deleted, and the key will expire in milliseconds
Pexpireat key milliseconds timestamp key expired after a nanosecond timestamp
TTL command can view the remaining expiration time of the key Hello, unit: seconds (> 0 remaining expiration time; – 1 no expiration time set; – 2 key does not exist)
Pttl is milliseconds

192.168.225.129:6379> expire k2 100
(integer) 1
192.168.225.129:6379> ttl k2
(integer) 91
192.168.225.129:6379> ttl ma
(integer) -1
192.168.225.129:6379>
6. The data structure type of the key
Type keyIf the key Hello is a string type, string is returned; if the key does not exist, none is returned

7. Key rename
rename key newkey
Rename x key newkey will be overridden only when newkey does not exist

8. Returns a key at random
randomkey

9. Migration key
(1) Move key DB moves the specified key from the source database to the target database
(2)dump+restore
dump key
Restore key ttl value
Dump + restore can realize the function of data migration between different redis instances. The whole migration process is divided into two steps;
1) On the source redis, the dump command serializes the key values in RDB format
2) On the target redis, the restore command restores the values serialized above, where TTL parameter represents expiration time and TTL = 0 represents no expiration time
example:

Source redis
192.168.225.129:6379> get redis
“world”
192.168.225.129:6379> dump redis
“x00x05worldax00xe6xe3xe9wxd8cxa7xd8”
Target redis
192.168.225.128:6379> get redis
(nil)
192.168.225.128:6379> restore redis 0 “x00x05worldax00xe6xe3xe9wxd8cxa7xd8”
OK
192.168.225.128:6379> get redis
“world”
(3)migrate
In fact, migrate is a combination of dump, restore and del, which simplifies the operation steps.
Migrate host port key [ key ……] destination-db timeout [replace]
Execution in source redis
192.168.225.129:6379> migrate 192.168.225.128 6379 flower 0 1000 replace
(migrate the key flower to the library 0 of the target 192.168.225.128:6379, the timeout is 1000 ms, and replace means that if the key flower exists in the target library, it will be overridden.)

10. Traversal key
(1) Total ergodic key
keys pattern
For example: keys h, keys [R, l] edits, keys, etc

(2) Progressive traversal
Scan can effectively solve the blocking problem of keys command. The complexity of scan is O (1)

Database management
1. Switch database
select dbIndex
There are 16 databases by default: 0-15. After entering redis, the default is 0. Multiple databases are not recommended

2、flushdb / flushall
It is used to clear the database. Flushdb only clears the current database and flushall clears all databases.

2、 Operation for key
1. Set value o (1)
set key value [ex] [px] [nx|xx]
Set the second level expiration time for the key value
PX sets the millisecond level expiration time for the key value
The NX key must not exist before it can be set successfully for adding
XX is the opposite of NX. The key must exist before it can be set successfully for updating
Setnx and setex have the same function as NX and ex above
2. Get value o (1)
Nil if get key does not exist

3. Batch set value o (k)
mset key value [key value ……]
mset a 1 b 2 c 3 d 4

4. Get the value o (k) in batch, where k is the number of keys
mget key [key ……]

5. Counting o (1)
incr key
decr key /inceby key increment /decrby key increment
The returned results are divided into three cases
The value is not an integer and an error is returned;
The value is an integer and returns the result after self increment;
The key does not exist. It increases automatically according to the value of 0, and the return result is 1.

6. Additional value o (1)
Append key value can append a value to the end of the string

7. String length o (1)
strlen key
Each Chinese character occupies 3 bytes

8. Set and return the original value o (1)
getset key value

9. Sets the character o (n) at the specified position, where n is the length of the string
setrange key offeset value
192.168.225.129:6379> get liming
“class4”
192.168.225.129:6379> setrange liming 0 m
(integer) 6
192.168.225.129:6379> get liming
“mlass4”
192.168.225.129:6379>
10. Get partial string
Getrange key start end start and end are the start and end offsets respectively, and the offset starts from 0

3、 Hash operation
1. Set value
hset key field value
The hsetnx command is also provided
Eg:hset user:1 name tom

2. Get value
hget key field

192.168.225.129:6379> hset user:1 name Tom
(integer) 1
192.168.225.129:6379> hget user:1 name
“Tom”
192.168.225.129:6379> hget user:1 age
(nil)
3. Delete field
HDEL key field [field…] will delete one or more fields, and the return result is the number of successfully deleted fiels

4. Calculate the number of fields
hlen key

5. Batch setting or getting field value
Hmget key field [field ……]
Hmset key field value [field value]

6. Determine whether the field exists
hexists key field

7. Get all fields
hkeys key

192.168.225.129:6379> hkeys user:1
1) “name”
2) “age”
3) “grand”
4) “city”
8. Get all values
hvals key

192.168.225.129:6379> hvals user:1
1) “Tom”
2) “20”
3) “3”
4) “beijing”
9. Get all the fields and values
hgetall key

10. The hincrby hincrbyfloat scope is field
hincrby key field
hincrbyfloat key field

11. Calculates the length of the value string
hstrlen key field

4、 List operation
List type originally stores multiple ordered strings, which can be repeated

The four operation types in the list
Operation type operation
Add rpush, lpush, linsert
Check lrange, lindex, llen
Delete lpop, rpop, lrem, ltrim
Modify lset
Blocking operation blpop, brpop
1. Add
(1) Insert element from right
rpush key value [value……]

(2) Insert element from left
lpush key value [value……]

(3) Insert an element before or after an element
linsert key before|after pivot value
The linsert command will find an element equal to pivot from the list and insert a new element value before or after it

192.168.225.129:6379> rpush mylist a b c d e f b a
(integer) 8
192.168.225.129:6379> linsert mylist after f g
(integer) 9
192.168.225.129:6379> lrange mylist 0 -1
1) “a”
2) “b”
3) “c”
4) “d”
5) “e”
6) “f”
7) “g”
8) “b”
9) “a”
2. Find
(1) Gets the list of elements in the specified range
The index subscripts of lrange key start end are 0 to n-1 from left to right and – 1 to – N from right to left; the end option contains itself
Lrange key 0 – 1 can get all the elements of the list from left to right
Lrange mylist 1 3 gets the second to fourth elements in the list

(2) Gets the element with the specified subscript in the list
lindex key index

(3) Get list length
llen key

3. Delete
(1) Pop up elements from the right side of the list
rpop key

(2) Pop up elements from the left side of the list
lpop key

(3) Delete the specified element
lrem key count value
The lrem command will find the element of = value from the list and delete it. According to the difference of count, it can be divided into three cases

When count > 0, the maximum number of count elements is deleted from left to right
For count < 0, from right to left, delete up to count absolute value elements
To delete all items, count = 0
The list listaaa is a Java PHP B
192.168.225.129:6379> lrem listaaa 5 a
(integer) 5
192.168.225.129:6379> lrange listaaa 0 -1
1) “java”
2) “php”
3) “b”
4) “b”
192.168.225.129:6379> lrem listaaa 3 php
(integer) 1
192.168.225.129:6379> lrange listaaa 0 -1
1) “java”
2) “b”
3) “b”
4. Modification
Lset key index newvalue modifies the element of the specified index subscript
Eg: lset listaa1 Python output as Java Python B

5. Blocking operation
blpop key [key …] timeout
brpop key [key …] timeout
Blpop and brpop are the blocking versions of lpop and rpop. Except for the different pop-up modes, they are basically the same in using methods, and the blocking time is almost the same

(1) The list is empty
brpop list:test 3 Return in 3 seconds
brpop list:test 0 It’s stuck all the time

(2) The list is not empty
Brpop mylist 0 returns immediately

192.168.225.129:6379> brpop mylist 0
1) “mylist”
2) “a”
5、 Set operation (non repeatable)
Operations within a collection
1. Add element
Sadd key element [element…..] returns the number of elements successfully added

2. Delete element
SREM key element [element…..] returns the number of elements successfully deleted

3. Calculate the number of elements
The time complexity of scar key scar is O (1), and the internal variables of redis are used directly

4. Determine whether the element is in the collection
Sismember key element returns 1 in the collection, otherwise it returns 0

5. Returns a specified number of elements from a collection at random
Srandmember key [count] count can not be written. The default value is 1

6. Pop elements randomly from set
Spop key [count] 3.2 supports [count]

7. Get all elements
Smembers key, lrange and hgetall are relatively heavy commands, which can sometimes be completed by sscan

Operations between sets
1. Finding the intersection of multiple sets
2. Finding union of multiple sets
3. Find the difference set sdiff key [key…] of multiple sets. What is in the first key and what is not in the second key
4. Save the results of intersection, union and difference
sinterstore destination key [ key ……]
sunionstore destination key [ key ……]
sdiffstore destination key [ key ……]
For example: sinterstore user:1_ 2:inter user:1 user :2 user:1_ 2: Incr is also a collection type

6、 Zadd operation (ordered set)
In set
1. Add member time complexity O (log (n)), Sadd is O (1)
Zadd key score member [score member…..] returns the number of elements successfully added

2. Calculate the number of members
The time complexity of zcard key scar is O (1), and the internal variables of redis are used directly

3. Calculate a member’s score
zsore key member

4. Calculate the ranking of members
zrank key member

5. Delete member
zrem key member [member …….]

6. Increase the score of members
zincrby key increment member

7. Returns the members of the specified ranking range
Zrange key start end [WithCores] from low score to high score
Zrevrange key start end [WithCores] from high score to low score

8. Returns the members of the specified score range
Zrange key min max [WithCores] [limit offset count] from low score to high score
Zrevrange key max min [WithCores] [limit offset count] according to the score, from high score to low score

9. Returns the number of members in the specified score range
zcount key min max

10. Delete the ascending elements in the specified rank
zremrangebyrank key start end

11. Delete members of the specified score range
zremrangebystore key min max

Operations between sets
1. Intersection
2. Union
3. Difference set
4. Save the results of intersection, union and difference
7、 Pub / sub (publish, subscribe)
1. Publish channel message eg: publish channel:sports ‘I want to go eatting’
2. Subscribe channel [channel…..] subscribe message eg: Subscribe channel:sports
3. Unsubscribe channel [channel…..] unsubscribe
4. Psubscribe pattern [pattern…] subscribe by pattern
5. Unsubscribe pattern [pattern…] unsubscribe by pattern
6. Query subscription
PubSub channels view active channels
192.168.225.128:6379> pubsub channels
1) “channel:sports”
2) “__sentinel__:hello”
PubSub numpub [channel…] view channel subscriptions PubSub numpub channel:sports
Number of PubSub numpat view mode subscriptions
7. Note:
After executing the subscription command, the client enters the subscription state and can only receive four commands: subscribe, psubscribe, unsubscribe and punsubscribe;
The newly opened subscription client cannot receive the message before the channel, because redis will not persist the published message.
8、 Transaction
8.1 discard to cancel all commands in the transaction block
8.2 exec to execute the command in the transaction block
8.3 multi, marking the beginning of a transaction block
8.4 UN watch, cancel the watch command to monitor all keys
8.5 watch key [key…] monitors one or more keys. If the Kye is moved by other commands before the transaction is executed, the transaction will be interrupted
9、 Connection
9.1 auth password, enter the password when logging in redis
9.2 echo message, print a specific message, and use it in the test
9.3 Ping to test the connection with the server. If it is normal, it returns pong
9.4 quit, request the server to close the connection with the current client
9.5 select index, switch to the specified database
10、 Server (server)
10.1 bgsave, save data to hard disk asynchronously in background
10.2 client setname / client getname to set and obtain the name for the connection
10.3 client kill IP: port, close the client with IP: port address
10.4 client list, which returns all connection client information and statistics in a human readable way
10.5 config get parameter to get the configuration parameters of running redis server
10.6 config set parameter value to set the configuration parameters of the redis server
10.7 config resetstat to reset some statistics of info command
10.8 dbsize, which returns the number of keys in the current database
10.9 flush, clear the data of the entire redis server (delete all keys of all databases)
10.10 flushdb to clear all keys in the current database
10.11 info [section], which returns various information and statistical data of redis server
10.12 lastsave, which returns the last time redis successfully saved the data to disk
10.13 monitor to print out the instructions received by the redis server in real time
10.14 save to save all the data snapshots of the current redis instance to the hard disk in the form of RDB file
10.15 slave of host port, which transforms the current server into the secondary server of the specified server
10.16 slowlog subcommand [argument], a log system used by redis to record query execution time

Recommended Today

Review of SQL Sever basic command

catalogue preface Installation of virtual machine Commands and operations Basic command syntax Case sensitive SQL keyword and function name Column and Index Names alias Too long to see? Space Database connection Connection of SSMS Connection of command line Database operation establish delete constraint integrity constraint Common constraints NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY DEFAULT […]