Redis study notes
The environment
[root@master ~]# cat /etc/redhat-release
CentOS Linux release 7.9.2009 (Core)
Copy the code
Linux install Redis
wget http://download.redis.io/redis-stable.tar.gz
tar xzf redis-stable.tar.gz
cd redis-stable
make
Copy the code
Error “make” :
[root@master redis-stable]# make
cdSRC && make all make[1]: enter directory /root/redis-stable/ SRC CC adlist.o /bin/sh: CC: not found make[1]: Make [1]: leave directory '/root/redis-stable/ SRC' make: *** [all] error 2Copy the code
Cause: No GCC environment exists in the system.
# yum install GCC
yum install gcc-c++ -y
Clear the files left over from the last compilation failure
make distclean
Copy the code
An error similar to the following is reported:
Server.c :5346:31: error: 'struct redisServer' does not have member redisSetCpuAffinity(server.server_cpulist) named 'server_cpulist';Copy the code
Solutions:
gcc -v Check the GCC version
yum -y install centos-release-scl Upgrade to version 9.1
yum -y install devtoolset-9-gcc devtoolset-9-gcc-c++ devtoolset-9-binutils
scl enable devtoolset-9 bash # This is temporary, if you want to use GCC 9.1 for a long time:
echo "source /opt/rh/devtoolset-9/enable" >>/etc/profile
Copy the code
If the installation is successful:
Hint: It's a good idea to run 'make test';) Make [1]: leave directory /root/redis-stable/ SRCCopy the code
Run make test if the following error occurs:
[root@master redis-stable]# make test
cd src && make testMake [1]: Makefile. Dep make[1]: Makefile. Dep make[1]: Makefile. Go to the directory /root/redis-stable/ SRC You need TCL 8.5 or newerin order to run the Redis test
make[1]: *** [testMake [1]: leave directory '/root/redis-stable/ SRC' make: *** [testError 2]Copy the code
Solutions:
yum install tcl -y
Copy the code
Make test succeeded, installation succeeded!!
Connect to Redis
After the make command is executed, a compiled redis service program redis-server and a client program redis-cli are displayed in /root/redis-stable/ SRC
Start the Redis service
./redis-server Start redis using the default configuration./redis-server .. /redis.conf# specify the profile to start
Copy the code
Interact with the Redis service using the test client program Redis – CLI
[root@master ~]# cd /root/redis-stable/src
[root@master src]# ./redis-cli127.0.0.1:6379 >Copy the code
Redis configuration file
Check the configuration
On the server
grep -Ev "$| ^ ^ #" redis.conf
Copy the code
On the client side
Get and set all Redis configurations using the Redis CONFIG command
Gets the CONFIG GET CONFIG_SETTING_NAME for an item
127.0.0.1:6379 > CONFIG GET loglevelCopy the code
Gets all configuration Settings
127.0.0.1:6379 > CONFIG GET *Copy the code
Edit the configuration
On the server
Edit the redis. Conf file directly
On the client side
The CONFIG set command updates the configuration
Redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUECopy the code
Common Configuration Items
Port 6379 If it is Intranet, you can directly bind 127.0.0.1 or ignore it. Daemonize yes # timeout 300 loglevel notice # Databases 16 save 900 1 save 300 10 Save 60 10000 rdbcompression yes # dbfilename dump. RDB # password abcd123 requirePass abcd123Copy the code
Redis data type
String (string)
Binary security: The length is known and is not affected by any special terminating characters
Store up to 512 megabytes of content in a string
Create and retrieve
127.0.0.1:6379> SET name "redis.com.cn"
OK
127.0.0.1:6379> GET name
"redis.com.cn"
127.0.0.1:6379>
Copy the code
Hash
A hash is a collection of key-value pairs
A hash is a mapping between string fields and string values
Fit to represent objects
Create and retrieve
127.0.0.1:6379> HMSET user:1 username ajeet password javatpoint alexa 2000
OK
127.0.0.1:6379> HGETALL user:1
1) "username"
2) "ajeet"
3) "password"
4) "javatpoint"
5) "alexa"
6) "2000"
Copy the code
Each hash can store up to 2^32-1 field-value pairs
List
A Redis list is defined as a list of strings, sorted in insertion order, and elements can be added to the head or tail of a Redis list.
Create and retrieve
127.0.0.1:6379> lpush skill java
(integer) 1
127.0.0.1:6379> lpush skill redis
(integer) 2
127.0.0.1:6379> lpush skill mongodb
(integer) 3
127.0.0.1:6379> lrange skill 0 2
1) "mongodb"
2) "redis"
3) "java"
Copy the code
The maximum length of the list is 2^32 — 1 element (over 4 billion elements)
Set
Unordered string collection
Add, delete, and find time is order one.
Create and retrieve
127.0.0.1:6379> sadd tutoriallist redis
(integer) 1
127.0.0.1:6379> sadd tutoriallist sql
(integer) 1
127.0.0.1:6379> sadd tutoriallist postgresql
(integer) 1
127.0.0.1:6379> sadd tutoriallist postgresql
(integer) 0
127.0.0.1:6379> smembers tutoriallist
1) "sql"
2) "postgresql"
3) "redis"
Copy the code
The maximum number of members in the set is 2^32-1 elements (over 4 billion elements)
Sorted set (sorted set)
Each member of a sorted set is associated with a score.
You can repeat fractions.
Minimum to maximum score.
Create and retrieve
127.0.0.1:6379> zadd skilllist 0 redis
(integer) 1
127.0.0.1:6379> zadd skilllist 0 sql
(integer) 1
127.0.0.1:6379> zadd skilllist 1 postgresql
(integer) 1
127.0.0.1:6379> zadd skilllist 2 momgodb
(integer) 1
127.0.0.1:6379> ZRANGEBYSCORE skilllist 0 10
1) "redis"
2) "sql"
3) "postgresql"
4) "momgodb"
Copy the code
Bitmaps
Stores 0 or 1 (bits) as values in a map-like structure
State of statistical
create
127.0.0.1:6379> setbit AAA :001 10001 1 (integer) 0 127.0.0.1:6379> setbit AAA :001 10002 0 (integer) 0 127.0.0.1:6379> setbit aaa:001 10003 1 (integer) 0Copy the code
Cardinal statistics (HyperLogLogs)
You can take multiple elements as inputs and give a cardinality estimate for the input elements
Even if the number or volume of input elements is very, very large, the space required to calculate the cardinality is always fixed and small
Create and retrieve
127.0.0.1:6379> PFADD Unique :: IP ::counter '192.168.0.1' (integer) 1 127.0.0.1:6379> PFADD Unique :: IP ::counter '127.0.0.1' (integer) 1 127.0.0.1:6379> PFADD unique:: IP ::counter '255.255.255.255' (integer) 1 127.0.0.1:6379> PFCOUNT unique::ip::counter (integer) 3Copy the code
Redis command
The login
redis-cli -h host -p port -a password
[root@master SRC]#./redis-cli -h 192.168.108.133 -p 6379 192.168.108.133:6379>Copy the code
Shut down the Redis server
127.0.0.1:6379 > shutdownCopy the code
The server will print: 39194:M 16 Dec 2020 10:59:17.585 # Redis is now ready to exit, bye bye…
Redis command keys
Grammar:
COMMAND KEY_NAME
Copy the code
The command | describe |
---|---|
DEL | Delete key |
DUMP | Serializes the given key and returns the serialized value |
EXISTS | Checks whether the given key exists |
EXPIRE | Sets the expiration time for a given key |
EXPIREAT | Used to set the expiration time for the key. The accepted time parameter is a UNIX timestamp |
PEXPIRE | Set the expiration time of the key in milliseconds |
PEXPIREAT | Set the timestamp (Unix timestamp) of the key expiration time, in milliseconds |
KEYS | Find all keys that match the given pattern |
MOVE | Moves the key of the current database to the given database |
PERSIST | When you remove the expiration time of a key, the key persists |
PTTL | Returns the remaining expiration time of the key in milliseconds |
TTL | Returns, in seconds, the remaining lifetime of a given key ( |
RANDOMKEY | Returns a random key from the current database |
RENAME | Change the name of the key |
RENAMENX | Change the name of the key to newkey only when newkey does not exist |
TYPE | Returns the type of the value stored by key |
String command
The command | describe |
---|---|
SET | Sets the value of the specified key |
GET | Gets the value of the specified key |
GETRANGE | Returns a subcharacter of the string value in key |
GETSET | Set the given key to value and return the old value of the key. |
GETBIT | Returns the bit at the specified offset for the string value stored by key. |
MGET | Gets the values of all (one or more) of the given keys |
SETBIT | Sets or clears the bits at the specified offset for the string value held by key. |
SETEX | Set key to value and expiration time to seconds |
SETNX | Set the key value only if the key does not exist |
SETRANGE | Overwrites the string value stored by the given key with value starting at offset |
STRLEN | Returns the length of the string value stored by key |
MSET | Set one or more key-value pairs at the same time |
MSETNX | Set one or more key-value pairs at the same time |
PSETEX | Sets the lifetime of the key in milliseconds |
INCR | Increment the value of the number stored in the key by one |
INCRBY | Add the value stored in the key to the given increment |
INCRBYFLOAT | Add the value stored by key to the given floating point increment |
DECR | Subtract the number stored in the key by one |
DECRBY | Decrement decreases the values stored in the key from the specified decrement value |
APPEND | Appends value to the end of the original key value |
Hash commands
The command | describe |
---|---|
HDEL | Deletes one or more hash table fields |
HEXISTS | Check whether the specified field in the hash table key exists |
HGET | Gets the value of the specified field stored in the hash table |
HGETALL | Gets all the fields and values of the specified key in the hash table |
HINCRBY | Add increment to the integer value of the specified field in the hash table key |
HINCRBYFLOAT | Increments the floating point value of the specified field in the hash table key |
HKEYS | Gets all fields in the hash table |
HLEN | Gets the number of fields in the hash table |
HMGET | Gets the values of all given fields |
HMSET | Set multiple field-value pairs into the hash key at the same time |
HSET | Set the value of field in hash table key to value |
HSETNX | Set the value of the hash table field only if the field field does not exist |
HVALS | Gets all values in the hash table |
HSCAN | Iterates key-value pairs in a hash table |
HSTRLEN | Returns the string length of the value in the hash key associated with the given field |
A list of commands
The command | describe |
---|---|
BLPOP | Removes and gets the first element of the list |
BRPOP | Removes and gets the last element of the list |
BRPOPLPUSH | Pop up a value from the list, insert it into another list and return it |
LINDEX | Gets the elements in the list by index |
LINSERT | Inserts an element before or after the element in the list |
LLEN | Get the list length |
LPOP | Removes and gets the first element of the list |
LPUSH | Inserts one or more values into the list header |
LPUSHX | Inserts a value into the head of an existing list |
LRANGE | Gets the elements in the specified range of the list |
LREM | Remove list elements |
LSET | Set the value of a list element by index |
LTRIM | Trim a list |
RPOP | Removes and gets the last element of the list |
RPOPLPUSH | Removes the last element of the list and adds it to another list and returns |
RPUSH | Adds one or more values to the list |
RPUSHX | Add a value to an existing list |
The set command
The command | describe |
---|---|
SADD | Adds one or more members to a collection |
SCARD | Gets the number of members of the collection |
SDIFF | Returns the difference set of all sets given |
SDIFFSTORE | Returns the difference set for a given collection and stores it in destination |
SINTER | Returns the intersection of all sets given |
SINTERSTORE | Returns the intersection of all the given collections and stores them in destination |
SISMEMBER | Check whether the member element is a member of the collection key |
SMEMBERS | Returns all members of the collection |
SMOVE | Move the member element from the source collection to the Destination collection |
SPOP | Removes and returns a random element from the collection |
SRANDMEMBER | Returns one or more random numbers in a collection |
SREM | Removes one or more members of a collection |
SUNION | Returns the union of all given sets |
SUNIONSTORE | The union of all given collections is stored in the Destination collection |
SSCAN | Iterate over the elements in the collection |
Ordered set command
The command | describe |
---|---|
ZADD | Adds one or more members to an ordered collection, or updates the scores of existing members |
ZCARD | Gets the number of members of an ordered collection |
ZCOUNT | Computes the number of members in an ordered set with a specified interval fraction |
ZINCRBY | Increment the score of a specified member in an ordered set |
ZINTERSTORE | Computes the intersection of one or more ordered sets given and stores the result set in a new ordered set key |
ZLEXCOUNT | Computes the number of members in the specified dictionary range in an ordered collection |
ZRANGE | Returns an ordered collection of the members of a specified interval through an indexed interval |
ZRANGEBYLEX | Returns a member of an ordered collection through a dictionary interval |
ZRANGEBYSCORE | Returns an ordered set of members within a specified interval by a fraction |
ZRANK | Returns the index of the specified member in the ordered collection |
ZREM | Removes one or more members of an ordered collection |
ZREMRANGEBYLEX | Removes all members of the given dictionary range from the ordered collection |
ZREMRANGEBYRANK | Removes all members of the given rank range from the ordered collection |
ZREMRANGEBYSCORE | Removes all members of the given fractional interval from the ordered set |
ZREVRANGE | Returns the members of an ordered set in a specified interval, indexed from high to bottom |
ZREVRANGEBYSCORE | Returns the members of the ordered set within the specified range of scores, sorted from highest to lowest |
ZREVRANK | Returns the ranking of the specified members of an ordered set, ordered in decreasing order (from largest to smallest) by score value |
ZSCORE | Returns the score value of a member in an ordered set |
ZUNIONSTORE | The union of one or more ordered sets is computed and stored in a new key |
ZSCAN | Iterating over elements in an ordered set (including element members and element scores) |
The transaction
Redis transaction execution is not atomic.
192.168.108.133:6379> multi
(error) DENIED Redis is running in protected mode because protected mode is enabled
Copy the code
Solution: Disable the protected mode
vim redis.conf
protected-mode no
Copy the code
Restart the redis
The instance
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> EXEC
(empty array)
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> SET rediscomcn redis
QUEUED
127.0.0.1:6379> GET rediscomcn
QUEUED
127.0.0.1:6379> INCR visitors
QUEUED
127.0.0.1:6379> EXEC
1) OK
2) "redis"
3) (integer) 1
Copy the code
Redis – check – aof tools
The command | describe |
---|---|
DISCARD | Cancels the transaction, abandoning all commands in the transaction block |
EXEC | Execute all commands within the transaction block |
MULTI | Marks the start of a transaction block |
UNWATCH | Unmonitor all keys with the WATCH command |
WATCH | Monitor one (or more) keys |
Redis script
Use the Lua interpreter to execute the script
Connection command
The command | describe |
---|---|
AUTH password | Verify that the password is correct |
ECHO message | Print string |
PING | Check whether the service is running |
QUIT | Close the current connection |
SELECT index | Switch to the specified database |
Manage commands related to redis service
The command | describe |
---|---|
BGREWRITEAOF | Perform an AOF (AppendOnly File) File rewrite asynchronously |
BGSAVE | Asynchronously saves the current database data to disk in the background |
CLIENT | Close the client connection |
CLIENT LIST | Gets a list of client connections to the server |
CLIENT GETNAME | Gets the name of the connection |
CLIENT PAUSE | Terminates the execution of a command from a client within the specified time |
CLIENT SETNAME | Sets the name of the current connection |
CLUSTER SLOTS | Gets a mapping array of cluster nodes |
COMMAND | Gets an array of Redis command details |
COMMAND COUNT | Gets the total number of Redis commands |
COMMAND GETKEYS | Gets all keys for a given command |
TIME | Returns the current server time |
COMMAND INFO | Gets an array of descriptions for the specified Redis command |
CONFIG GET | Gets the value of the specified configuration parameter |
CONFIG REWRITE | Modify the redis.conf configuration file |
CONFIG SET | Modify redis configuration parameters without restart |
CONFIG RESETSTAT | Reset some statistics in the INFO command |
DBSIZE | Returns the number of keys in the current database |
DEBUG OBJECT | Obtain key debugging information |
DEBUG SEGFAULT | Crash the Redis service |
FLUSHALL | Delete all keys for all databases |
FLUSHDB | Delete all keys from the current database |
INFO | Get all kinds of information and statistics of Redis server |
LASTSAVE | Returns the last time that Redis successfully saved data to disk |
MONITOR | Real – time print Redis server received command, debugging |
ROLE | Returns the role to which the primary and secondary instances belong |
SAVE | Asynchronously saves data to disks |
SHUTDOWN | Asynchronously saves data to hard disk and shuts down server |
SLAVEOF | Convert the current server to a slave server |
SLOWLOG | Manage slow logs in Redis |
SYNC | Internal command for replication |
Backup and Restore
The backup
The SAVE command creates a backup of the current database
127.0.0.1:6379 > SAVE OKCopy the code
The dump. RDB file is generated after the SAVE command is executed.
[root@master src]# find -name "dump.rdb"
./dump.rdb
Copy the code
restore
Move the Redis backup file (dump.rdb) to the Redis directory and start the server
Find the Redis installation directory
127.0.0.1:6379> config get dir 1) "dir" 2) "/root/redis-stable/ SRC"Copy the code
BGSAVE
security
Authentication sets the password for the instance
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) ""127.0.0.1:6379 > configsetRequirepass "javatpoint123" OK 127.0.0.1:6379> CONFIG get requirepass 1)"requirepass"
2) "\xe2\x80\x9cjavatpoint123\xe2\x80\x9d"127.0.0.1:6379 >Copy the code
The following error occurs during authentication
127.0.0.1:6379> AUTH javatpoint123
(error) WRONGPASS invalid username-password pair
Copy the code
The reason:
1: used before Redis6.0. Default user. AUTH <password> 2: new mode, also need to verify the username AUTH <username> <password>Copy the code
View the Redis version
# the service side
[root@master ~]# cd redis-stable/src/
[root@master src]# ./redis-server -vRedis server V =6.0.9 SHA =00000000:0 malloc= jemalloc-5.1.0bits =64 build= a207EE3C635211f0 [root@master SRC]# ./redis-server --versionRedis server V =6.0.9 SHA =00000000:0 MALloc = jemalloc-5.1.0bits =64 build= a207EE3C635211f0# client127.0.0.1:6379 > info# ServerRedis_version: 6.0.9Copy the code
Set the password and authentication for the instance
127.0.0.1:6379> ACL SETUSER zhoujy on > ABC OK 127.0.0.1:6379> ACL SETUSER zhoujy on # 6 d970874d0db767a7058798973f22cf6589601edab57996312f2ef7b56e5584d OK 127.0.0.1:6379 > ACL GETUSER zhoujy 1) "flags" 2) 1) "on" 3) "passwords" 4) 1) "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" 2) "6d970874d0db767a7058798973f22cf6589601edab57996312f2ef7b56e5584d" 5) "commands" 6) "-@all" 7) "keys" 8) (empty array) 127.0.0.1:6379> AUTH zhoujy ABC OK 127.0.0.1:6379> AUTH zhoujy CBA OKCopy the code
The benchmark
Check Redis performance
options | describe | The default value |
---|---|---|
-h | Specify the server host name | 127.0.0.1 |
-p | Specify server port | 6379 |
-s | Specify server socket | |
-c | Specifies the number of concurrent connections | 50 |
-n | Specify number of requests | 10000 |
-d | Specifies the data size of a SET/GET value in bytes | 2 |
-k | 1keep alive 0reconnect | 1 |
-r | SET/GET/INCR uses random keys and SADD uses random values | |
-p | The request is piped | 1 |
-q | Forced exit from Redis. Only query/ SEC values are displayed | |
–csv | Output in CSV format | |
-l | Generate a loop that executes the test permanently | |
-t | Run only a comma-separated list of test commands | |
-I | Idle mode. Open only N IDLE connections and wait |
Example:
[root@master SRC]#./redis-benchmark -h 127.0.0.1 -p 6379 -t set,lpush -n 100000 -q ERROR: NOAUTH Authentication required. ERROR: Failed to fetch CONFIG from 127.0.0.1:6379 WARN: Could not fetch server CONFIG SET: 183823.52 requests per second LPUSH: 182815.36 requests per secondCopy the code
Client connection
Maximum number of clients
127.0.0.1:6379> Config get maxclients
(error) NOPERM this user has no permissions to run the 'config' command or its subcommand
Copy the code
Solution:?
The command | describe |
---|---|
CLIENT LIST | Returns a list of clients connected to the Redis service |
CLIENT SETNAME | Sets the name of the current connection |
CLIENT GETNAME | Gets the service name set using the CLIENT SETNAME command |
CLIENT PAUSE | Suspend the client connection, specifying the duration of suspension in milliseconds |
CLIENT KILL | Close the client connection |