Executable file under bin
- Redis-server: indicates the redis server
- Redis -cli: command line client
- Redis-benchmark: Redis performance test tool
- Redis-check-aof: aOF file repair tool
- Redis-check-dump: RDB file detection tool
- Redis-sentinel: used for primary backup
Start and stop Redis
- The following boot modes are available
- Start without loading configuration:
redis-server
- Load configuration startup:
redis-server /etc/redis.conf
- Start with Docker:
Run - d - rm - v/root/test/redis conf: / redis conf - name redis - test - p, 6379:6379 redis: 5.0.0
- Start without loading configuration:
- There are several ways to stop
- Run the command line after redis is connected
shutdown
- End the Redis process directly:
kill ...
- Stop Docker startup redis:
docker stop redis-test
- Run the command line after redis is connected
Command return value type
- State the reply
- Write a
SET
Command reply OK - write
PING
Command reply to “pong”
- Write a
- Error response
- Both begin with (error)
- Integer reply
- All begin with (integer), such as increment commands
- String reply
- GET a key returns a value
- Multi-line string reply
- Each line begins with a serial number
- For example, the command
KEYS *
Gets the key name in the current database
- Return null result
- GET a nonexistent key, or GET a null key, returns nil.
Configuration options
- This can be set dynamically (when the service is started, or modified after it is started), or through a configuration file. Dynamic Settings override configuration file Settings
- You can do this by command
CONFIG GET Indicates the configuration name
The first line is the configuration name and the second line is the value - through
CONFIG SET Configuration name value
Modify the configured value
Common Simple Commands
Common commands for connection operations
# close the connection
>quit
# Simple password authentication
>auth xxxxx
# return various information and statistics for redis server
#info [section]
> INFO CPU
# CPUUsed_cpu_user used_cpu_sys: 0.082652:0.125159 used_cpu_sys_children: used_cpu_user_children 0.000949:0.002533Copy the code
- Returns all connected client information and statistics in a human-readable manner
> Client list ID =3 addr=127.0.0.1:57516 fd=8 Name = age=101 IDLE =0 FLAGS =N DB =0 sub=0 psub=0 multi=-1 QBUf =26 qbuf-free=32742 obl=0 oll=0 omem=0 events=r cmd=clientCopy the code
- Save the data synchronization to disk, and then shut down the service stop process
>shutdown
Copy the code
- Real time printing out the instructions received by the Redis server
>monitor
OK
Copy the code
Persist common commands
- Synchronize data to disk
> save
OK
Copy the code
- Data is asynchronously saved to disk
> bgsave
Background saving started
Copy the code
- Returns the last Unix timestamp that successfully saved data to disk
> lastsave
(integer) 1557285566
Copy the code
This section describes how to configure common commands
-
Config get parameter # run redis server config parameter
-
Config set parameter value # Set redis server configuration parameters
-
Gets the current log level configuration
> CONFIG GET loglevel
1) "loglevel"
2) "notice"
Copy the code
- Get port configuration
> CONFIG GET port
1) "port"
2) "6379"
Copy the code
- Changing the log level (supported log levels debug, verbose, NOTICE, and Warning)
>CONFIG SET loglevel debug
OK
Copy the code
- Write the redis configuration in memory to the redis.conf file on disk
>config rewrite
Copy the code
Slow log related commands
- Reset slow logging
> SLOWLOG RESET
OK
Copy the code
- Example Query slow logs
Query the first 10 slow logs (default: 10) > SLOWLOG GET 10 (empty list or)set)
Copy the code
- Returns the number of slow logs
> SLOWLOG LEN
(integer) 0
Copy the code
Common commands for database operations
- In Redis, the database is named by a number. The number of the first database is 0, for example, to enter database 1
127.0.0.1:6379> SELECT 1
OK
127.0.0.1:6379[1]>
Copy the code
- Query all keys of the current library
>KEYS *
Copy the code
- Returns a random key
>randomkey
Copy the code
- Query the total number of keys directly obtain redis built-in total number of keys variable
>dbsize
Copy the code
- Get all keys in the database
127.0.0.1:6379[1]> KEYS *
(empty list or set) 127.0.0.1:6379 [1] >Copy the code
- Clear all keys in the current database
>FLUSHDB
Copy the code
- Clear all keys in all databases
>FLUSHALL
Copy the code
- The migration KEY
Dump+restore enables data migration between different Redis instances. The whole migration process is divided into two steps.
#1) On source Redis, dump serializes the key values in RDB format
#2) On the target redis, the restore command restores the values serialized above, where the TTL parameter represents the expiration time and TTL =0 represents no expiration time192.168.225.129:6379 > get redis"world"192.168.225.129:6379 > dump redis"\x00\x05world\a\x00\xe6\xe3\xe9w\xd8c\xa7\xd8"Target redis 192.168.225.128:6379> get redis (nil) 192.168.225.128:6379> restore redis 0"\x00\x05world\a\x00\xe6\xe3\xe9w\xd8c\xa7\xd8"OK 192.168.225.128:6379 > get redis"world"
Dump: dump: restore: del: dump: restore: del
#Migrate host port key [ key ......] destination-db timeout [replace]
[rootflower] [rootflower] [rootflower] [rootflower] [rootflower] [rootflower] [rootflower]
192.168.225.129:6379> migrate 192.168.225.128 6379 flower 0 1000 replace
Copy the code
Common active/standby commands
- The redis instance is used as a slave to clear the current data and copy the data from the master instance.
- grammar
slaveof <masterip> <masterport>
> slaveof 192.168.0.100 6379Copy the code
- Upgrade slave to master. This operation deletes the original slave
slaveof <masterip> <masterport>
Configuration and Readonly configuration
>slaveof no one
Copy the code
Configuration file redis.conf
The basic configuration
# monitor port
port 6379
Start as a daemon
daemonize yes
Listen to the IP address
bind 127.0.0.1
Set which IP address Redis exposes to visitors (for NAT networking)
cluster-announce-ip "192.168.0.8"
# How long does the client wait for no operation to automatically disconnect? Set 0 to not automatically disconnect
timeout 0
# log level
# Specify the server verbosity level.
# This can be one of:
# debug (a lot of information, useful for development/testing)
# verbose (many rarely useful info, but not a mess like the debug level)
# notice (moderately verbose, what you want in production probably)
# warning (only very important / critical messages are logged)
loglevel notice
Set pid file path
pidfile "/cache1/redis/data/redis.pid"
Write a path or empty the output to stdout. However, if it is run as a daemon and empty, the log is written to /dev/null
logfile ""
# limit the number of databases that can be set. By default, only 16 are allowed. The first database number is 0
databases 16
# MaxMemory-policy specifies the maximum memory that can be used. When redis memory data sets approach MaxMemory, Redis implements a data obsolescence policy
maxmemory 0
#Redis offers 6 data elimination strategies:
#volatile-lru: selects the least recently used data from the memory data set with expiration time;
#volatile- TTL: selects expiring data from memory sets with expiring time;
#volatile-random: randomly selects data from a memory set with expiration time;
# allkeys-lRU: select the least recently used data from the memory data set;
#allkeys-random: randomly select data from the dataset;
#no-enviction: Disallow expulsion of data. (Default elimination policy. When redis reaches maxMemory, an OOM error is returned.
maxmemory-policy volatile-lru
# To prevent a script from taking so long that Redis cannot provide services (such as getting stuck in an infinite loop), Redis provides the lua-time-limit parameter to limit the maximum running time of the script. The default is 5 seconds. When the script runs longer than this limit, Redis will start accepting additional commands but will not execute them (to ensure atomicity of the script, since the script has not been terminated), but will return a "BUSY" error.
lua-time-limit 5000
Set the maximum number of clients that can be connected at the same time. The default is 0 and there is no limit. This configuration is related to the number of file descriptors that the Redis process can open
Redis will close all new connections and return error "Max number of clients reached"
maxclients 10000
Read multiple configuration files, useful when there is a standard configuration template but each Redis instance needs personalized Settings
include /path/to/local.conf
include /path/to/other.conf
Copy the code
Slowly querying related configurations
If the command execution time exceeds this value, redis will record it as slow query
# Disable slow query logs if the value is set to negative
If the value is 0, record all commands
slowlog-log-slower-than 10000
# set the length of the slow query log. If the log is full, delete the oldest log and keep the latest one
You can use the SLOWLOG RESET command to free memory
slowlog-max-len 128
Copy the code
Buffer Configuration
In order to solve the hidden danger of large accumulation of messages in the output buffer, Redis sets up some protection mechanisms, mainly using two restrictions:
- Size limit, when a client buffer exceeds the set value directly after closing the connection;
- Persistence limit, which closes a connection when a client buffer takes up too much space for a period of time.
The format of the configuration item is as follows: client-output-buffer-limit
The specific meanings of parameters are as follows:
- Class: client type, normal, slave, pubSub.
- Mormal: Normal client
- Slave: indicates the replication client of the slave library
- Pub /sub: Publish and subscribe client
- Hard Limit: Indicates the hard limit of the buffer size.
- Soft limit: indicates the soft limit of buffer size.
- Soft seconds: specifies the duration for which the buffer size reaches or exceeds the soft limit value, in seconds.
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
Copy the code
Configurations related to RDB snapshots
The biggest disadvantage of the snapshot method is that when the Redis process dies unexpectedly, the most recent data will be lost (how much data will be lost depending on your save policy configuration). When there is a lot of traffic, a lot of data is lost
# save
If a key is changed within 900 seconds, save the snapshot (persistent drop disk) to the database file on disk
save 900 1
Snapshot with 10 changes in 300 seconds
save 300 10
Snapshot with 10,000 changes in 69 seconds
save 60 10000
# whether to use compression when storing local databases, default yes, use LZF algorithm. Compression consumes CPU, while non-compression consumes disk space
rdbcompression yes
# The filename where to dump The DB The file name on disk of the local database
dbfilename dump.rdb
Starting with RDB version 5, a CRC64 check is placed at the end of the file.
# This makes the format more resistant to attacks, but there is a 10% or so performance drop when storing or loading RBD files,
# So, for maximum performance, you can turn this configuration off.
RDB files with no checksum will have a 0 check bit to tell the loading code to skip the checksum check.
rdbchecksum yes
The default directory is the current directory
dir ./
Redis will stop accepting updates when persistence fails. The update operation is resumed if the persistence process is working again
If the background persistence fails, the Redis update operation continues
stop-writes-on-bgsave-error yes
Copy the code
Configurations related to AOF persistence
-
The append-only method does not lose all data, but redis is less efficient. The principle is to record every write operation in the form of a log, and record all write instructions performed by Redis (read operations are not recorded). Only files can be appended but files can not be overwritten. When Redis starts, it reads the file to rebuild data, in other words, When redis is restarted, write instructions are executed from front to back according to the contents of the log file to complete data recovery.
-
When the AOF file size exceeds a set threshold, Redis will compress the contents of the AOF file, retaining only the smallest instruction set that can recover data. You can use the command bgrewriteaof
-
Rewriting Principle If an AOF file grows too large, a new process is forked to rewrite the file (also write temporary files first and rename the file last), and the data in the memory of the new process is traversed. Each record has a Set statement. The operation of overwriting an AOF file, rather than reading the old AOF file, commands the entire contents of the database in memory to rewrite a new AOF file, similar to a snapshot
# open AOF
appendonly yes
Set the AOF file name
appendfilename "appendonly.aof"
#AOF drop mode optional parameters are:
Always always write to aOF file and complete disk synchronization
Everysec writes aOF files every second and completes disk synchronization
#no Writes to aOF file without waiting for disk synchronization
Always is the safest from a persistence perspective. In terms of efficiency, No is the fastest. The redis default is a compromise, choosing Everysec.
appendfsync always
# appendfsync request writes only to buffer without dropping when rewriting AOF files. (If the current AOF file is large, then rewrite will take longer and appendfsync will be blocked for longer, and service exceptions will lose data during this time.)
no-appendfsync-on-rewrite yes
Rewrite is triggered when the AOF file size is more than 100% (double) of the previous one and the file size is larger than 64M
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
#redis ignores the last possible problem instruction when restoring, default yes. A sudden power outage during aOF writing can result in an instruction error (written halfway), in which case yes will log and continue, while no will directly resume failure
aof-load-truncated yes
Copy the code
Security-related Configuration
The slave instance needs to access the master when the sentinel active/standby Redis or Cluster is running, so the master instance password needs to be configured on the slave instance
masterauth "d9s@@ddd"
# this Redis password
requirepass "saseawe"
Rename or disable dangerous commands
# For example, disable FLUSHALL
rename-command FLUSHALL ""
FLUSHDB: FLUSHDB: FLUSHDB: FLUSHDB: FLUSHDB: FLUSHDB: FLUSHDB: FLUSHDB: FLUSHDB: FLUSHDB: FLUSHDB
rename-command FLUSHDB qf69aZbLAX3cf3ednHM3SOlbpH71yEXLAX3cf3e
Copy the code
Primary/secondary configurations
Configure the IP address and port of the primary database. The primary database from which the standby database replicates data. If this setting is enabled on the standby database, data on the standby database will be cleared before replication startsSlaveof 192.168.0.100 6379# as a slave server, it is read-only by default (yes). It can be changed to NO for writing (not recommended).
slave-read-only yes
The connection between the slave and master is interrupted
#yes indicates that the slave will continue to answer requests from the client even if the data is out of date.
All client requests except INFO and SLAVEOF will only respond with "SYNC with master in progress" until the connection between the slave and master is restored or the slave is promoted to master
slave-serve-stale-data yes
After being deployed in Replication mode, the slave will PING packets to the master at a predetermined interval (default: 10 seconds). This configuration can change the default interval
repl-ping-slave-period 10
Bulk Transfer I/O timeout; Bulk Transfer I/O timeout; 2) Master data or ping response timeout.
If the default value is changed, the value entered by the user must be greater than the value set by rep-ping-slave-period. Otherwise, timeout will occur frequently when the master/slave link delay is high.
repl-timeout 30
# When yes is configured, NO_DELAY will be disabled. TCP stack will merge packets and send them uniformly. This will reduce the number of packets between master and slave nodes and save bandwidth, but will increase the time of data synchronization to slave
# When NO_DELAY is enabled when no is configured, TCP stack will not delay the packet sending time, so the delay of data synchronization will be reduced, and more bandwidth will be consumed
In the case of sufficient bandwidth, it is recommended to set it to NO to reduce synchronization delay
repl-disable-tcp-nodelay no
# In the case of multiple slaves, Redis Seninel selects the slave with the lowest priority value to be promoted to master when the master is down
If this configuration is 0, sentinel will never be promoted to master
slave-priority 4
Copy the code
Redis-cluster configuration
Enable cluster mode
cluster-enabled yes
Path to the cluster configuration file
cluster-config-file "nodes.conf"
# cluster timeout
cluster-node-timeout 5000
Copy the code
Advanced optimized configuration
# Hash code a Hashtable (which requires more memory) is appropriate when there is a large amount of data, and the number of elements cannot exceed the given limit. You can set these limits with the following options:
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
# Similar to hashing, you can save a lot of space by encoding Ziplist in another way with fewer data elements. This method should only be used if the following restrictions are met:
list-max-ziplist-entries 512
list-max-ziplist-value 64
# Data is a string of 64-bit unsigned integer numbers. The following configuration item limits the maximum number of encodings that can be used in this case.
set-max-intset-entries 512
Similar to the first and second cases, ordered sequences can also be handled in a special encoding way, which can save a lot of space. This encoding applies only to ordered sequences whose length and elements meet the following constraints:
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
The default is 10 hash table refreshes per second to refresh the dictionary and then free memory as soon as possible.
# Suggestion: Use "Activerehashing no" if you're concerned with delays; Set "Activerehashing Yes" if you don't care about latency and want to free memory as quickly as possible.
activerehashing yes
Limiting the client output buffer forces clients that do not read data from the server to disconnect.
For normal Client, the first 0 means hard limit is removed, the second 0 and the third 0 means soft limit is removed, and normal Client defaults to soft limit because they will not receive data without asking.
client-output-buffer-limit normal 0 0 0
For slave and MONITER clients, if the client-outoutput buffer exceeds 256MB, or if it exceeds 64MB for 60 seconds, the server immediately disconnects the client.
client-output-buffer-limit slave 256mb 64mb 60
For Pubsub client, if the client-output-buffer exceeds 32MB, or if it exceeds 8MB for 60 seconds, the server will immediately disconnect the client.
client-output-buffer-limit pubsub 32mb 8mb 60
Copy the code
Configuration file sentinel.conf
In a redis environment with one master and many slaves, multiple sentinels can be used to maintain the security of the data. Sentinels monitor both the master and slave databases and each other
The configuration is as follows
Start as a daemon
daemonize yes
The default listening port is 26379
port 26379
Master database IP and port number. Sentinel automatically changes this configuration when the master changes
# the 2 at the end indicates that at least several sentinels are required to agree before a failover operation can be performed. This is typically set to N/2+1(N is the total number of sentinels).Sentinel Monitor Redis-Master 192.168.1.51 7000 2# specifies the number of milliseconds needed for Sentinel to determine that the server is offline
sentinel down-after-milliseconds redis-master 5000
If the master does not respond after the specified time, sentinel will remove the failed instance. If the master has recovered, sentinel will treat the failed master as a slave
sentinel failover-timeout redis-master 900000
The # option specifies the maximum number of slave servers that can synchronize with the new master server during failover, and the smaller the number, the longer the failover will take to complete.
sentinel parallel-syncs redis-master 2
Master access password
sentinel auth-pass redis-master 123456
#log file path
logfile "./sentinel.log"
Copy the code
Data types and data manipulation commands in Redis
String String type
A key can store a maximum of 512MB
- Relevant command
SET
Set the key value to value, EX to the key lifetime, PX to the unit of milliseconds, NX to the unit of milliseconds, and XX to the unit of milliseconds- grammar
SET Key value [EX seconds] [PX millisconds] [NX|XX]
- case
>SET testStr1 'this is a test' OK >SET testS2 'test2' OK > SET username xiaoming EX 10 OK > SET username xiaoming PX 1000000000 OK > PTTL username (integer) 999986009 > GET username "xiaoming" > SET username erha NX (nil) > GET username "xiaoming" > SET username erha XX OK > GET username "erha" Copy the code
- case
- grammar
GET
Find the corresponding value based on key- Returns if the result is empty
(nil)
- An error is returned if the key value is not a string
(error) WRONGTYPE Operation against a key holding the wrong kind of value
- case
>GET testStr1 "this is a test" >LPUSH testList1 a b c (integer) 3 > GET testList1 (error) WRONGTYPE Operation against a key holding the wrong kind of value Copy the code
- Returns if the result is empty
GETRANGE
Returns a portion of the string- grammar
GETRANGE Key Start point End point
- case
>GET testStr2 "meizitu" # returns the first character through the fifth character >GETRANGE testStr2 0 4 "meizi" Return the first character to the penultimate character >GETRANGE testStr2 0 -2 "meizit" # return the first character to the third to last character >GETRANGE testStr2 0 -3 "meizi" # return the penultimate character to the penultimate character >GETRANGE testStr2 -4 -2 "zit" If the end point is earlier than the start point, only null results will be returned >GETRANGE testStr2 -4 -5 "" If the end point is longer than the string, only the end of the string is returned >GETRANGE testStr2 0 1000 "meizitu" Copy the code
- grammar
GETSET
Sets the value of the specified key and returns the old value- grammar
GETSET key value
- case
>SET testStr3 'winter' OK >GET testStr3 "winter" >SET testStr3 'is' OK >GETSET testStr3 'comming' "is" # if getSet does not have a key, return nil >GETSET testStr4 'this is a test' (nil) Copy the code
- grammar
MSET
Set multiple key-value pairs at once- grammar
MSET key value [ key value ...]
- case
>MSET testStr5 'king' testStr6 'meizi' testStr7 'queen' OK Copy the code
- grammar
MGET
Get multiple key-value pairs at once- grammar
MGET key key key ...
- case
> MGET testStr5 testStr6 testStr7 testStr8 1) "king" 2) "meizi" 3) "queen" 4) (nil) Copy the code
- grammar
STRLEN
Gets the length of the key string- Grammar:
STRLEN key
- case
> SET testStr5 'king' OK > STRLEN testStr5 (integer4)Return length 0 if used for a key that does not exist > STRLEN testStr6 (integer) 0 Copy the code
- Grammar:
SETRANGE
Replaces a portion of a string with another value and returns the modified length of the string- grammar
SETRANGE key offset value
- case
# If the character position is null, it will be treated as null > SET testStr9 "hello king" OK > SETRANGE testStr9 6 'queen' (integer) 11 > GET testStr9 "hello queen" # check whether the key exists. Return 0 for non-existence, return 1 for existence > EXISTS testStr10 (integer) 0 > EXISTS testStr9 (integer1)# SETRANGE for nonexistent keys returns 0 characters > SETRANGE testStr10 5 'king' (integer) 9 > GET testStr10 "\x00\x00\x00\x00\x00king" Copy the code
- grammar
SETNX
NS indicates not exist. The parameter can be set successfully only when the key does not exist- grammar
SETNX key value
- case
# if the key does not exist, it can be set successfully and return integer 1 >EXISTS testStr11 (integer) 0 >SETNX testStr11 'meizi' (integer) 1 >GET testStr11 "meizi" Return integer 0 if setting key already exists >SETNX testStr11 'king' (integer) 0 >GET testStr11 "meizi" Copy the code
- grammar
SETEX
Is atomic operation, set the expiration time of the key, set the survival time and set the value in the same action to complete- grammar
SETEX key seconds Time value Specifies the time value
- case
>SETEX expireStr 60 'testExpire' OK Use the TTL command to see how much time is left for the key to expire > TTL expireStr (integer51)If the key does not exist, TTL will return integer -2 > TTL expireStr (integer) -2 > GET expireStr (nil) # Separate the two actions >SET expireStr1 'test1' OK >EXPIRE expireStr1 10 (integer) 1 >TTL expireStr1 (integer5)# If you use SETEX on an existing key, the original value and timeout will be overwritten >SETEX test12, 1000'a' OK >GET test12 "a" >TTL test12 (integer) 991 >SETEX test12, 100'b' OK >TTL test12 (integer) 97 >GET test12 "b" Copy the code
- grammar
MSETNX
Setting multiple key values at a time is similar to MSET, but can be set successfully only when the key does not exist. If one key exists, all keys fail to be set. Integer 1 is returned on success, integer 0 is returned on failure- grammar
MSETNX key value [key value ...]
- case
>MSETNX test13 'a' test14 'b' test15 'c' (integer) 1 >MGET test13 test14 test15 (1)"a" 2) "b" 3) "c" >MSETNX test15 'aa' test16 'bb' test17 'cc' (integer) 0 >MGET test13 test14 test15 test16 test17 (1)"a" 2) "b" 3) "c" 4) (nil) 5) (nil) Copy the code
- grammar
PSETEX
Similar to setex, P is used to set the lifetime of a key in millisecondsPTTL
Obtain the remaining lifetime of the key- PSETEX key milliseconds value
- case
>PSETEX test16, 2000'hello world' OK >PTTL test16 (integer) 210 >PTTL test16 (integer2) -Copy the code
INCR
If the key does not exist, the value is initialized to 0 before INCR is executed. An error is reported if the value is out of range or not an integer- grammar
INCR key
- case
>SET counter 1 OK >INCR counter (integer) 2 >INCR counter (ingeger) 3 # INCR is used as if the value is 0 when used for a non-existent key > GET test (nil) > EXISTS test (integer) 0 > INCR test (integer1)# use INCR for string > SET test20 'hello google' OK > INCR test20 (error) ERR value is not an integer or out of range Copy the code
- grammar
INCRBY
Adds the number stored in the key to the specified integer increment (only integer numbers are supported, not floating point numbers)- grammar
INCRBY key number
- case
> SET counter2 10 OK > INCRBY counter2 5 (integer15)Copy the code
- grammar
INCRBYFLOAT
Adds the number stored in the key to the specified floating-point increment (optionally an integer number)- Syntax ‘ ‘INCRBY key INCREMENT’
- case
> SET counter3 1 OK > INCRBYFLOAT counter3 1.2 "2.2" > INCRBYFLOAT counter3 5 "7.2" Copy the code
DECR
Subtract 1 from the number stored in the key- grammar
DECR key
- case
>SET counter2 12 >DECR Counter2 (integer13)Copy the code
- grammar
DECRBY
Increments the number stored in the key by the specified integer (integer only, not floating point)- grammar
DECRBY key decrement
- case
>GET counter2 "13" >DECRBY counter2 3 (integer10)# > DECRBY counter2 1.2 (error) ERR value is not an integer or out of range Copy the code
- grammar
APPEND
Appends a string to the end of a value, or executes a SET operation if key does not exist- grammar
APPEND key value
- case
>GET testStr11 "meizi" >APPEND testStr11 'edu' (integer) 8 >GET testStr11 "meiziedu" >APPEND noExistsStr 'this is a test' (integer) 14 >GET noExistsStr "this is a test" Copy the code
- grammar
Hash type
Also known as hash tables. It’s also a set of key-value pairs. This applies to storing objects. Hash objects to save memory
- Related configuration files:
hash-max-ziplist-entries 512
Hash specifies the maximum number of bytes to store hashhash-max-ziplist-value 64
The number of fields stored by the hash type. The default 64
- Relevant command
HSET
Example Set the field in the hash key to the specified value- grammar
HSET key field value
- case
If a field does not exist, a new field will be created, which will return integer 1 > HSET userInfo1 username 'king' (integer1)# Reassign and return integer 0 when field already exists > HSET userInfo1 username 'king2' (integer) 0 > HSET userInfo1 password '123456' (integer) 1 > HSET userInfo1 email '[email protected]' (integer1)Copy the code
- grammar
HGET
Returns the value of the field specified in the hash table key- grammar
HGET key field
- case
> HGET userInfo1 username "king" > HGET userInfo2 username (nil) Copy the code
- grammar
HSETNX
The value is assigned when the field in the hash table does not exist, equivalent to not exsist- grammar
HSETNX key field value
- case
>HSETNX testHash1 test 'a' (integer) 1 >HSETNX testHash1 test '111' (integer) 0 Copy the code
- grammar
HMSET
Example Set multiple field-values to keys in the hash table at the same time- grammar
HMSET key field value field value ...
- case
>HMSET userInfo2 username 'king' password '123' nickname 'smart king' email '[email protected]' OK If the field already exists, a rerun will overwrite it > HMSET userInfo2 username 'queen' role 'admin' OK Copy the code
- grammar
HMGET
Retrieves the value of multiple fields in the hash key at once, and returns nil if none of the fields in the key exist- grammar
HMGET key field field field ...
- case
> HMGET userInfo2 username password email nickname test 1) "queen" 2) "123" 3) "[email protected]" 4) "smart king" 5) (nil) Copy the code
- grammar
HGETALL
Returns all fields and values in the hash key, with odd rows being keys and even rows being values- grammar
HGETALL key
- case
>HGETALL userInfo2 1) "username" 2) "queen" 3) "password" 4) "123" 5) "nickname" 6) "smart king" 7) "email" 8) "[email protected]" 9) "role" 10) "admin" Copy the code
- grammar
List the type
List type, is a simple list of strings, sorted by insertion order, store up to 2 ^ 32 minus 1 element, implemented by a two-way list, get elements as close as possible faster.
- Relevant command
LPUSH
Adds elements to the left end of the list, one or more at a time- Syntax ‘LPUSH key value value…”
- case
Verify that the list does not exist > EXISTS myList1 (integer) 0 Add 3 elements to the list > LPUSH myList a b c (integer) 3 # Add 3 more elements to the list for a total of 6 elements > LPUSH myList c d e (integer6)See from the first element to the last > LRANGE myList 0 -1 1) "e" 2) "d" 3) "c" 4) "c" 5) "b" 6) "a" Copy the code
RPUSH
Add an element to the right end of the list- grammar
RPUSH key value ...
- case
> RPUSH myList test1 test2 test3 (integer) 9 > LRANGE myList 0 -1 1) "e" 2) "d" 3) "c" 4) "c" 5) "b" 6) "a" 7) "test1" 8) "test2" 9) "test3" Copy the code
- grammar
RPUSHX
LPUSHX
Same as above, but only if the key exists- case
> RPUSHX myList test1 test2 test3 (integer) 12 > LPUSHX myList test1 test2 test3 (integer) 15 > LRANGE myList 0 -1 1) "test3" 2) "test2" 3) "test1" 4) "e" 5) "d" 6) "c" 7) "c" 8) "b" 9) "a" 10) "test1" 11) "test2" 12) "test3" 13) "test1" 14) "test2" 15) "test3" > LPUSHX myList2 test1 test2 test3 (integer) 0 Copy the code
- case
LPOP
Pops an element in the head of the list- grammar
LPOP key
- case
> LRANGE myList 0 -1 1) "test3" 2) "e" 3) "c" 4) "test3" # pop header test3 > LPOP myList "test3" > LRANGE myList 0 -1 1) "test3" 2) "e" 3) "c" 4) "test3" Copy the code
- grammar
RPOP
Pops an element from the tail of the list- grammar
RPOP key
- grammar
LLEN
Gets the length of the list, which is the number of listed elements- grammar
LLEN key
- case
> LRANGE myList 0 -1 1) "test2" 2) "test1" 3) "e" 4) "d" 5) "c" 6) "c" 7) "b" 8) "a" 9) "test1" 10) "test2" 11) "test3" 12) "test1" 13) "test2" 14) "test3" >LLEN myList (integer14)# Return 0 if the list does not exist > LLEN myList4 (integer) 0 Copy the code
- grammar
LRANGE
Gets a fragment of the list where 0 represents the first element of the list, 1 represents the second element of the list, -1 represents the last element, and the complex number represents counting backwards- grammar
LRANGE key start stop
- case
> LRANGE myList 0 -1 1) "test2" 2) "test1" 3) "e" 4) "d" 5) "c" 6) "c" 7) "b" 8) "a" 9) "test1" 10) "test2" 11) "test3" 12) "test1" 13) "test2" 14) "test3" Get the first element > LRANGE myList 0 0 1) "test2" 127.0.0.1:6379> LRANGE myList 0 2 1) "test2" 2) "test1" 3) "e" Get elements from left to right > LRANGE myList -1 -3 (empty list or set) Get the last three elements > LRANGE myList -3 -1 1) "test1" 2) "test2" 3) "test3" Copy the code
- grammar
LREM
Delete the specified parameter from the list.- grammar
LREM key count value
- Count has the following types:
- If count is greater than 0, start at the top of the list and work your way to the end, remove as many elements as value, remove count
- If count is less than 0, search from tail to head, remove elements equal to value, remove count
- Count equals 0 removes all values equal to value from the list
- case
Create a list and assign a value > LPUSH myList2 a b c d a e b c d b e f b g e b (integer) 16 > LLEN myList2 (integer16)Delete 2 b's from the search > LREM myList2 2 b (integer) 2 127.0.0.1:6379> LRANGE myList2 0 -1 1) "e" 2) "g" 3) "f" 4) "e" 5) "b" 6) "d" 7) "c" 8) "b" 9) "e" 10) "a" 11) "d" 12) "c" 13) "b" 14) "a" # Remove 2 as from tail search127.0.0.1:6379> LREM myList2-2 a (integer) 2 127.0.0.1:6379> LRANGE myList2 0 -1 1) "e" 2) "g" 3) "f" 4) "e" 5) "b" 6) "d" 7) "c" 8) "b" 9) "e" 10) "d" 11) "c" 12) "b" Delete all e's from the list 127.0.0.1:6379> LREM myList2 0 e (integer) 3 127.0.0.1:6379> LRANGE myList2 0 -1 1) "g" 2) "f" 3) "b" 4) "d" 5) "c" 6) "b" 7) "d" 8) "c" 9) "b" Copy the code
- grammar
LINDEX
Retrieves the value of the specified index element and finds the value based on the index, followed by an integer that can be positive or negative- grammar
LINDEX key index start
- case
> LRANGE myList2 0 -1 1) "g" 2) "f" 3) "b" 4) "d" 5) "c" 6) "b" 7) "d" 8) "c" 9) "b" > LINDEX myList2 5 "b" > LINDEX myList2 -3 "d" > LINDEX myList2 0 "g" Copy the code
- grammar
LSET
Sets the value of the specified index element, based on the index- grammar
LSET
- case
> LRANGE myList2 0 -1 1) "g" 2) "f" 3) "b" 4) "d" 5) "c" 6) "b" 7) "d" 8) "c" 9) "b" > LSET myList2 0 king OK > LRANGE myList2 0 -1 1) "king" 2) "f" 3) "b" 4) "d" 5) "c" 6) "b" 7) "d" 8) "c" 9) "b" # Out of range > LSET myList2 110 king (error) ERR index out of range The key does not exist > LSET myList3 1 king (error) ERR no such key Copy the code
- grammar
LTRIM
Keep only the fragments of the list, delete everything else, only the elements between the start and end points, delete everything else- grammar
LTRIM key start stop
- case
> LRANGE myList3 0 -1 1) "log5" 2) "log4" 3) "log3" 4) "log2" 5) "log1" 127.0.0.1:6379> LTRIM myList3 0 1 OK 127.0.0.1:6379> LRANGE myList3 0 -1 1) "log5" 2) "log4" Copy the code
- grammar
LINSERT
Inserts an element into the list, before or after the pivot, and does nothing when the pivot does not exist- grammar
LINSERT key BEFORE|AFTER pivot value
- case
> LPUSH myList5 a b c d (integer4)# Insert king before b > LINSERT myList5 BEFORE 'b' 'king' (integer) 5 > LRANGE myList5 0 -1 1) "d" 2) "c" 3) "king" 4) "b" 5) "a" > LRANGE myList5 0 -1 1) "d" 2) "c" 3) "king" 4) "b" 5) "a" > LINSERT myList5 AFTER 'd' 'queen' (integer) 6 > LRANGE myList5 0 -1 1) "d" 2) "queen" 3) "c" 4) "king" 5) "b" 6) "a" Copy the code
- grammar
- Set Set type
- Zset Ordered collection type
- Other Common Commands
KEYS
Returns keys for all given schemas- grammar
KEYS pattern
- The wildcard
- * Matches any character
- ? Matches an arbitrary character
- [] matches a character between []
- \ Translate special characters
- grammar
EXISTS
Checks whether the specified key exists- grammar
EXISTS key
TYPE
Returns the type stored in the key- grammar
TYPE key
- The return type
- Returns None for nonexistent keys
- string
- hash
- set
- zset
- list
EXPIRE
Set the expiration time of the key. If you run the command on a key that already has the state-owned time, the time will be reset. In version 2.4, the key remained valid for 1 second after expiration. In version 2.6, the key became accessible within 1 millisecond after expiration- grammar
EXPIRE key seconds
- case
Set failure returns 0 > EXPIRE cache_page 100 (integer) 0 > SET cache_page sl OK Return 1 on success > EXPIRE cache_page 100 (integer1)Use TTL to check the remaining time >TTL cache_page (integer) 88 Copy the code
- grammar
EXPIREAT
Set the expiration time of the key, setting the specific point in time (timestamp), not the time range- grammar
EXPIREAT key timestamp
- case
>SET cache_page1 'www.qq.com' OK >EXPIREAT cache_page1 1431868110 (integer1)Use TTL to check the remaining time >TTL cache_page1 (integer) 88 Copy the code
- grammar
PEXPIRE
Set the key expiration time in milliseconds- grammar
PEXPIRE key milliseconds
- use
PTTL
Query Remaining time
- grammar
PEXPIREAT
Set the expiration time of the key, setting the specific timestamp, not the range- grammar
PEXPIREAT key timestamp
- grammar
TTL
Returns the remaining expiration time of the key in seconds- grammar
TTL key
- If no expiration time is set for the key, -1 is returned
- If the key does not exist, -2 is returned
- grammar
PTTL
Returns the remaining expiration time of the key in millisecondsPERSIST
Change a key with an expiration time to a permanent key- grammar
PERSIST
- case
> SET cache 'testCache' OK > TTL cache (integer) -1 > EXPIRE cache 100 (integer) 1 > TTL cache (integer) 96 > PERSIST cache (integer) 1 > TTL cache (integer1) -Copy the code
- grammar
DEL
Remove the key- grammar
DEL key ...
- case
# select * from key >DEL cache1 cache2 cache3 (integer) 1 >DEL one two three four (integer4)Copy the code
- grammar
RANDOMKEY
Returns a random key from the current database- grammar
RANDOMKEY
- grammar
RENAME
Rename a key- grammar
RENAME key key
- case
> SET testRename1 'rename1'OK 127.0.0.1:6379 > RENAMEtestRename1 testRename2 OK 127.0.0.1:6379 > GETtestRename1 (nil) 127.0.0.1:6379 > GETtestRename2 "rename1"127.0.0.1:6379 > RENAMEtestRename2 testRename2 OK # Error if source key does not exist > RENAME testRens testRename2 (error) ERR no such key Copy the code
- grammar
RENAMENX
The renamed name is valid only if it does not exist- Syntax ‘RENAMENX key newkey’
DUMP
Serialize the given key and return the serialized value- grammar
DEMP key
- case
> SET testDump 'this is a test' OK > DUMP testDump "\x00\x0ethis is a test\t\x00 \x88)\xc7\xcef\xce\xda" Copy the code
- grammar
RESTORE
Deserialize the given key and return the deserialized value- grammar
RESTORE key ttl value
- case
Deserialization will set the expiration time > RESTORE testDump3 50000 "\x00\x0ethis is a test\t\x00 \x88)\xc7\xcef\xce\xda"OK 127.0.0.1:6379 > GETtestDump3 "this is a test"127.0.0.1:6379 > PTTLtestDump3 (integer) 42520 Copy the code
- grammar
MOVE
Move the key from the current database to another database. If the target database already exists, the move fails and an error is returned- grammar
MOVE key dbID
- case
Open database 0 127.0.0.1:6379> SELECT 0 OK 127.0.0.1:6379> SET testMove 'aaaa'OK 127.0.0.1:6379 > GETtestMove "aaaa" Open database 1 127.0.0.1:6379> SELECT 1 OK 127.0.0.1:6379[1]> KEYS * (empty list or set) 127.0.0.1:6379[1]> SELECT 0 OK 127.0.0.1:6379> MOVE testMove 1 (integer127.0.0.1) 1:6379 > GETtestMove (nil) 127.0.0.1:6379> SELECT 1 OK 127.0.0.1:6379[1]> GET testMove "aaaa" Copy the code
- grammar