Redis (1)

Time:2020-11-30

Redis

About redis

  • Remote dictionary server (redis) is a key value storage system. Redis is an open source log type, key value database written in ANSI C language, complying with BSD protocol, supporting network, memory based and persistent, and providing API in multiple languages. It is often referred to as a data structure server, because values can be strings, hashes, lists, sets, and sorted sets.

  • Redis and other key value caching products have the following three characteristics:

    • Redis supports data persistence. It can save the data in memory on the disk, and can be loaded again for use when restarting.
    • Redis not only supports simple key value data, but also provides storage of list, set, Zset, hash and other data structures.
    • Redis supports data backup, that is, data backup in master slave mode.
  • Advantages of redis

    • High performance– redis can read 110000 times / s and write 81000 times / s.
    • Rich data types– redis supports string, lists, hashes, sets and ordered sets data type operations of binary cases.
    • atomAll operations of redis are atomic, which means that either they are executed successfully or they fail to be executed at all. Individual operations are atomic. It also supports multiple operations through exi and multi.
    • Rich featuresRedis also supports publish / subscribe, notification, key expiration, etc.
  • What is the difference between redis and other key value stores?

    • Redis has a more complex data structure and provides atomic operations on them, which is a different evolution path from other databases. Redis’s data types are based on the basic data structure and transparent to programmers without any extra abstraction.
    • Redis runs in memory, but it can be persisted to disk. Therefore, it is necessary to weigh the memory when reading and writing different datasets at high speed, because the data volume cannot be greater than the hardware memory. Another advantage of in memory database is that compared with the same complex data structure on disk, it is very simple to operate in memory, so redis can do many things with strong internal complexity. At the same time, in terms of disk format, they are produced in a compact way, because they do not require random access.

Ubuntu apt command installation

  • To install redis on the Ubuntu system, you can use the following commands:
# sudo apt update
# sudo apt install redis-server
  • Start redis
# redis-server
  • Check whether redis is started?
# redis-cli
  • The above command will open the following terminals:
redis 127.0.0.1:6379>
  • 127.0.0.1 is the local IP and 6379 is the redis service port. Now we enter the ping command.
redis 127.0.0.1:6379> ping
PONG

The above shows that we have successfully installed redis.

Redis configuration

The redis configuration file is located in the redis installation directory, and the file name isredis.conf(windows name is redis.windows.conf )。

You can go throughCONFIGCommand to view or set configuration items.

  • The syntax redis config command format is as followsredis 127.0.0.1:6379> CONFIG GET CONFIG_SETTING_NAME

example

redis 127.0.0.1:6379> CONFIG GET loglevel

1) "loglevel"
2) "notice"
  • Use * to get all configuration items:

example

redis 127.0.0.1:6379> CONFIG GET *

  1) "dbfilename"
  2) "dump.rdb"
  3) "requirepass"
  4) ""
  5) "masterauth"
  6) ""
  7) "unixsocket"
  8) ""
  9) "logfile"
 10) ""
 11) "pidfile"
 12) "/var/run/redis.pid"
 13) "maxmemory"
 14) "0"
 15) "maxmemory-samples"
 16) "3"
 17) "timeout"
 18) "0"
 19) "tcp-keepalive"
 20) "0"
 21) "auto-aof-rewrite-percentage"
 22) "100"
 23) "auto-aof-rewrite-min-size"
 24) "67108864"
 25) "hash-max-ziplist-entries"
 26) "512"
 27) "hash-max-ziplist-value"
 28) "64"
 29) "list-max-ziplist-entries"
 30) "512"
 31) "list-max-ziplist-value"
 32) "64"
 33) "set-max-intset-entries"
 34) "512"
 35) "zset-max-ziplist-entries"
 36) "128"
 37) "zset-max-ziplist-value"
 38) "64"
 39) "hll-sparse-max-bytes"
 40) "3000"
 41) "lua-time-limit"
 42) "5000"
 43) "slowlog-log-slower-than"
 44) "10000"
 45) "latency-monitor-threshold"
 46) "0"
 47) "slowlog-max-len"
 48) "128"
 49) "port"
 50) "6379"
 51) "tcp-backlog"
 52) "511"
 53) "databases"
 54) "16"
 55) "repl-ping-slave-period"
 56) "10"
 57) "repl-timeout"
 58) "60"
 59) "repl-backlog-size"
 60) "1048576"
 61) "repl-backlog-ttl"
 62) "3600"
 63) "maxclients"
 64) "4064"
 65) "watchdog-period"
 66) "0"
 67) "slave-priority"
 68) "100"
 69) "min-slaves-to-write"
 70) "0"
 71) "min-slaves-max-lag"
 72) "10"
 73) "hz"
 74) "10"
 75) "no-appendfsync-on-rewrite"
 76) "no"
 77) "slave-serve-stale-data"
 78) "yes"
 79) "slave-read-only"
 80) "yes"
 81) "stop-writes-on-bgsave-error"
 82) "yes"
 83) "daemonize"
 84) "no"
 85) "rdbcompression"
 86) "yes"
 87) "rdbchecksum"
 88) "yes"
 89) "activerehashing"
 90) "yes"
 91) "repl-disable-tcp-nodelay"
 92) "no"
 93) "aof-rewrite-incremental-fsync"
 94) "yes"
 95) "appendonly"
 96) "no"
 97) "dir"
 98) "/home/deepak/Downloads/redis-2.8.13/src"
 99) "maxmemory-policy"
100) "volatile-lru"
101) "appendfsync"
102) "everysec"
103) "save"
104) "3600 1 300 100 60 10000"
105) "loglevel"
106) "notice"
107) "client-output-buffer-limit"
108) "normal 0 0 0 slave 268435456 67108864 60 pubsub 33554432 8388608 60"
109) "unixsocketperm"
110) "0"
111) "slaveof"
112) ""
113) "notify-keyspace-events"
114) ""
115) "bind"
116) ""

Edit configuration

You can modify it redis.conf File or useCONFIG setCommand to modify the configuration.

  • grammar

CONFIG SETCommand basic syntax:

redis 127.0.0.1:6379> CONFIG SET CONFIG_SETTING_NAME NEW_CONFIG_VALUE

example

redis 127.0.0.1:6379> CONFIG SET loglevel "notice"
OK
redis 127.0.0.1:6379> CONFIG GET loglevel

1) "loglevel"
2) "notice"

Parameter configuration

  • redis.conf The configuration items are described as follows:
Serial number Configuration item explain
1 daemonize no Redis does not run as a daemon by default. It can be modified through this configuration item and enable the daemons with Yes (Windows does not support the configuration of daemons as no)
2 pidfile /var/run/redis.pid When redis runs as a daemon, redis writes PID to / var / run by default/ redis.pid File, which can be specified through pidfile
3 port 6379 Specify the redis listening port. The default port is 6379. Why use 6379 as the default port? 6379 is the number corresponding to Merz on the phone key, and Merz is taken from the name of Italian singer Alessia Merz. Merz has long been used as a synonym for stupidity by the redis author antiez and his friends. Later, the redis author chose this port when developing redis.
——Alessia Merz is an Italian dancer and actress. In the early years of watching TV programs, the author of redis thought that Merz’s words in the program were stupid and ridiculous. Antirez liked to make “stem” to communicate with friends, so he created a word “Merz” to describe stupidity, which has the same meaning as “stumpid”.
——Later, antirez redefined “Merz” to describe “as having high technical value, including skill, patience and labor, but still keeping the essence of simplicity”.
——When it comes to choosing a number for redis as the default port number, antirez didn’t think much about it and used the corresponding number 6379 of “Merz” on the mobile phone keyboard.
4 bind 127.0.0.1 Bound host address
5 timeout 300 When the client is idle for several seconds, the connection is closed. If 0 is specified, the function is turned off
6 loglevel notice Specify the logging level. Redis supports four levels in total: debug, hibernate, notice and warning. The default is notice
7 logfile stdout The logging mode is standard output by default. If redis is configured to run in the daemons mode and the logging mode is configured as standard output, the log will be sent to / dev / null
8 databases 16 Set the number of databases. The default database is 0. You can use the select command to specify the database ID on the connection
9 save The redis default configuration file provides three conditions:
save 900 1
save 300 10
save 60 10000
It means 1 change in 900 seconds (15 minutes), 10 changes in 300 seconds (5 minutes) and 10000 changes in 60 seconds.
Specify how long and how many update operations will synchronize the data to the data file, and multiple conditions can be matched
10 rdbcompression yes Specify whether to compress the data when storing to the local database. The default value is yes. Redis uses lzf compression. To save CPU time, you can turn off this option, but the database file will become huge
11 dbfilename dump.rdb Specifies the local database file name. The default value is dump.rdb
12 dir ./ Specify the local database storage directory
13 slaveof Set the IP address and port of master service when the local machine is slave service. When redis is started, it will automatically synchronize data from the master
14 masterauth When the master service is password protected, the slave service connects to the master password
15 requirepass foobared Set the redis connection password. If the connection password is configured, the client needs to use auth to connect to redisThe command provides a password, which is turned off by default
16 maxclients 128 Set the maximum number of client connections at the same time. There is no limit by default. The number of client connections that redis can open at the same time is the maximum number of file descriptors that can be opened by redis process. If maxclients 0 is set, there is no limit. When the number of client connections reaches the limit, redis will close new connections and return the max number of clients reached error message to the client
17 maxmemory Specify the maximum memory limit of redis. When the maximum memory is reached, redis will first try to clear the expired or about to be expired keys. After this method is processed, it still reaches the maximum memory setting, and can not write, but can still read. Redis’s new VM mechanism will store the key in memory and the value in the swap area
18 appendonly no Specifies whether to log after each update operation. By default, redis writes data asynchronously to the disk. If it is not turned on, it may cause data loss for a period of time during power failure. Because redis itself synchronizes data files according to the above save conditions, some data will only exist in memory for a period of time. The default is No
19 appendfilename appendonly.aof Specifies the update log file name. The default is appendonly.aof
20 appendfsync everysec Specifies the update log condition. There are three optional values:no: indicates to wait for the operating system to synchronize the data cache to the disk (fast)always: means to manually call fsync() to write data to disk after each update operation (slow, safe)everysec: indicates synchronization once per second (trade-off, default)
21 vm-enabled no Specify whether to enable the virtual memory mechanism. The default value is No. for a brief introduction, the VM mechanism stores the data in pages, and redis will swap the pages with less visits to the disk, that is, the cold data, and the pages with more visits are automatically swapped out of the disk to the memory (in the following article, I will carefully analyze the VM mechanism of redis)
22 vm-swap-file /tmp/redis.swap Virtual memory file path, the default value is / tmp/ redis.swap , cannot be shared by multiple redis instances
23 vm-max-memory 0 Save all data larger than VM Max memory into virtual memory. No matter how small VM Max memory is set, all index data are stored in memory (redis’s index data is keys). In other words, when VM Max memory is set to 0, all values exist on the disk. The default value is 0
24 vm-page-size 32 Redis swap file is divided into many pages. An object can be saved on multiple pages, but a page cannot be shared by multiple objects. VM page size should be set according to the size of the stored data. The author suggests that if many small objects are stored, the page size should be set to 32 or 64 bytes; if a large object is stored, a larger one can be used Page, if you’re not sure, use the default value
25 vm-pages 134217728 Set the number of pages in the swap file. Since the page table (a bitmap indicating that the page is idle or used) is placed in memory, every 8 pages on the disk will consume 1 byte of memory.
26 vm-max-threads 4 Set the number of threads accessing the swap file. It is better not to exceed the number of cores of the machine. If it is set to 0, all operations on the swap file are serial, which may cause a long delay. The default value is 4
27 glueoutputbuf yes Set whether to merge smaller packets into one package to send when replying to the client. It is enabled by default
28 hash-max-zipmap-entries 64 hash-max-zipmap-value 512 Specifies that a special hash algorithm is used when more than a certain number or the largest element exceeds a certain threshold
29 activerehashing yes Specifies whether to activate reset hash, which is enabled by default (I will introduce redis’s hash algorithm in detail later)
30 include /path/to/local.conf Specify to include other configuration files. You can use the same configuration file between multiple redis instances on the same host, and each instance has its own specific configuration

Redis data type

Redis supports five data types: string (string), hash (hash), list (list), set (set) and Zset (sorted set: ordered set).


String (string)

As like as two peas, string is the most basic type of redis. You can understand it as a type that is exactly the same as Memcached, and a key corresponds to a value.

String type is binary safe. This means that the string of redis can contain any data. For example, JPG images or serialized objects.

String type is the most basic data type of redis, and the value of string type can store 512MB at most.

example

redis 127.0.0.1:6379> SET runoob "huahua"
OK
redis 127.0.0.1:6379> GET runoob
"huahua"

In the above example, we use redis’sSETandGETCommand. The key is runoob and the corresponding value ishuahua

be careful:A key can store 512MB at most.

Redis string command details

The following table lists the common redis string commands:

Serial number Command and description
1 SET key valueSet the value of the specified key
2 GET keyGets the value of the specified key.
3 GETRANGE key start endReturns the sub character of the string value in the key
4 GETSET key valueSet the value of the given key to value and return the old value of the key.
5 GETBIT key offsetFor the string value stored by key, get the bit (bit) at the specified offset.
6 [MGET key1 key2..]Gets the values of all (one or more) given keys.
7 SETBIT key offset valueFor the string value stored by key, set or clear the bit at the specified offset.
8 SETEX key seconds valueAssociate the value value with the key and set the expiration time of the key to seconds (in seconds).
9 SETNX key valueSet the value of the key only if the key does not exist.
10 SETRANGE key offset valueUse the value parameter to override the string value stored by the given key, starting with the offset offset.
11 STRLEN keyReturns the length of the string value stored by the key.
12 [MSET key value key value …]Set one or more key value pairs at the same time.
13 [MSETNX key value key value …]Set one or more key value pairs simultaneously if and only if all the given keys do not exist.
14 PSETEX key milliseconds valueThis command is similar to the setex command, but it sets the lifetime of the key in milliseconds, rather than seconds, as in the setex command.
15 INCR keyIncrease the number value stored in the key by one.
16 INCRBY key incrementAdd the value stored in the key with the given increment value.
17 INCRBYFLOAT key incrementAdd the value stored in key to the given floating-point increment value.
18 DECR keySubtract one from the numeric value stored in the key.
19 DECRBY key decrementThe value stored in key is subtracted by the given decrement value.
20 APPEND key valueIf the key already exists and is a string, the append command appends the specified value to the end of the original value of the key.

Hash (hash)

Redis hash is a set of key value pairs (key = > value).

Redis hash is a mapping table of field and value of string type. Hash is especially suitable for storing objects.

DEL runoobUsed to delete the key used in the previous test. Otherwise, an error will be reported(error) WRONGTYPE Operation against a key holding the wrong kind of value

redis 127.0.0.1:6379> DEL runoob
redis 127.0.0.1:6379> HMSET runoob field1 "Hello" field2 "World"
"OK"
redis 127.0.0.1:6379> HGET runoob field1
"Hello"
redis 127.0.0.1:6379> HGET runoob field2
"World"

In the example, we use redisHMSET, HGETCommand,HMSETTwo are setfield=>valueYes, hget gets the correspondingfieldCorrespondingvalue

Each hash can store 232-1 key value pairs (more than 4 billion).

Redis hash command details

The following table lists the basic commands for redis hash:

Serial number Command and description
1 [HDEL key field1 field2]Delete one or more hash table fields
2 HEXISTS key fieldCheck whether the specified field exists in the hash table key.
3 HGET key fieldGets the value of the specified field stored in the hash table.
4 HGETALL keyGets all the fields and values of the specified key in the hash table
5 HINCRBY key field incrementAdds increment increment to the integer value of the specified field in the hash table key.
6 HINCRBYFLOAT key field incrementAdds increment increment to the floating-point value of the specified field in the hash table key.
7 HKEYS keyGets the fields in all hash tables
8 HLEN keyGets the number of fields in the hash table
9 [HMGET key field1 field2]Gets the value of all the given fields
10 [HMSET key field1 value1 field2 value2 ]Set multiple field value pairs into the hash table key at the same time.
11 HSET key field valueSet the value of field field in hash table key to value.
12 HSETNX key field valueSet the value of the hash table field only if the field field does not exist.
13 HVALS keyGets all the values in the hash table.
14 [HSCAN key cursor MATCH pattern] [COUNT count]Iterates the key value pairs in the hash table.

List

Redis list is a simple list of strings, sorted in insertion order. You can add an element to the head (left) or tail (right) of the list.

redis 127.0.0.1:6379> DEL runoob
redis 127.0.0.1:6379> lpush runoob redis
(integer) 1
redis 127.0.0.1:6379> lpush runoob mongodb
(integer) 2
redis 127.0.0.1:6379> lpush runoob rabitmq
(integer) 3
redis 127.0.0.1:6379> lrange runoob 0 10
1) "rabitmq"
2) "mongodb"
3) "redis"
redis 127.0.0.1:6379>

It can store up to 42964 billion elements (up to 94724 billion lists per list).

Redis list command details

The following table lists the basic commands related to the list:

Serial number Command and description
1 [BLPOP key1 key2 ] timeoutMove out and get the first element of the list. If there is no element in the list, the list will be blocked until the waiting time-out or the pop-up element is found.
2 [BRPOP key1 key2 ] timeoutMove out and get the last element of the list. If there is no element in the list, the list will be blocked until the waiting time-out or the pop-up element is found.
3 BRPOPLPUSH source destination timeoutPop up a value from the list, insert the pop-up element into another list and return it; if there is no element in the list, the list will be blocked until the waiting time-out or the pop-up element is found.
4 LINDEX key indexGet the elements in the list by index
5 LINSERT key BEFORE|AFTER pivot valueInsert an element before or after an element in the list
6 LLEN keyGet list length
7 LPOP keyMove out and get the first element of the list
8 [LPUSH key value1 value2]Inserts one or more values into the head of the list
9 LPUSHX key valueInserts a value into an existing list header
10 LRANGE key start stopGets the elements in the specified range of the list
11 LREM key count valueRemove element list
12 LSET key index valueSet the value of a list element through an index
13 LTRIM key start stopTrim a list, that is to say, only the elements in the specified range will be kept in the list, and the elements not in the specified range will be deleted.
14 RPOP keyRemove the last element of the list, and the return value is the removed element.
15 RPOPLPUSH source destinationRemoves the last element of the list and adds it to another list and returns
16 [RPUSH key value1 value2]Add one or more values to the list
17 RPUSHX key valueAdd a value to an existing list

Set (set)

Redis’s set is an unordered set of string type.

The collection is implemented by hash table, so the complexity of adding, deleting and searching is O (1).

Add command

Add a string element to the set set set corresponding to the key. 1 is returned successfully. If the element is already in the set, 0 is returned.

sadd key member

example

redis 127.0.0.1:6379> DEL runoob
redis 127.0.0.1:6379> sadd runoob redis
(integer) 1
redis 127.0.0.1:6379> sadd runoob mongodb
(integer) 1
redis 127.0.0.1:6379> sadd runoob rabitmq
(integer) 1
redis 127.0.0.1:6379> sadd runoob rabitmq
(integer) 0
redis 127.0.0.1:6379> smembers runoob

1) "redis"
2) "rabitmq"
3) "mongodb"

be careful:In the above example, rabitmq is added twice, but according to the uniqueness of the elements in the collection, the elements inserted the second time will be ignored.

The largest number of members in the collection is 232 – 1 (4294967295, each collection can store more than 4 billion members).

Redis set command

The following table lists the redis collection basic commands:

Serial number Command and description
1 [SADD key member1 member2]Add one or more members to the collection
2 SCARD keyGets the number of members of the collection
3 [SDIFF key1 key2]Returns the difference between the first collection and other collections.
4 [SDIFFSTORE destination key1 key2]Returns the difference set of all given sets and stores it in destination
5 [SINTER key1 key2]Returns the intersection of all given sets
6 [SINTERSTORE destination key1 key2]Returns the intersection of all given sets and stores it in destination
7 SISMEMBER key memberDetermine whether the member element is a member of the collection key
8 SMEMBERS keyReturns all members of the collection
9 SMOVE source destination memberMove the member element from the source collection to the destination collection
10 SPOP keyRemoves and returns a random element from the collection
11 [SRANDMEMBER key count]Returns one or more random numbers in a collection
12 [SREM key member1 member2]Remove one or more members from the collection
13 [SUNION key1 key2]Returns the union of all given sets
14 [SUNIONSTORE destination key1 key2]The union of all given sets is stored in the destination collection
15 [SSCAN key cursor MATCH pattern] [COUNT count]Elements in iteration sets

Zset (sorted set: ordered set)

Redis Zset, like set, is a collection of string type elements, and duplicate members are not allowed.

The difference is that each element is associated with a score of type double. Redis is to sort the members of a collection from small to large through scores.

The member of Zset is unique, but the score can be repeated.

Zadd command

Add an element to the collection. If an element exists in the collection, the corresponding score will be updated

zadd key score member

example

redis 127.0.0.1:6379> DEL runoob
redis 127.0.0.1:6379> zadd runoob 0 redis
(integer) 1
redis 127.0.0.1:6379> zadd runoob 0 mongodb
(integer) 1
redis 127.0.0.1:6379> zadd runoob 0 rabitmq
(integer) 1
redis 127.0.0.1:6379> zadd runoob 0 rabitmq
(integer) 0
redis 127.0.0.1:6379> > ZRANGEBYSCORE runoob 0 1000
1) "mongodb"
2) "rabitmq"
3) "redis"

Redis ordered set command

The following table lists the basic commands for redis ordered sets:

Serial number Command and description
1 [ZADD key score1 member1 score2 member2]Add one or more members to an ordered collection, or update scores for existing members
2 ZCARD keyGets the number of members of an ordered collection
3 ZCOUNT key min maxCalculates the number of members of a specified interval fraction in an ordered set
4 ZINCRBY key increment memberThe fraction of a specified member in an ordered set plus increment
5 [ZINTERSTORE destination numkeys key key …]The intersection of one or more ordered sets is calculated and the result set is stored in the new ordered set destination
6 ZLEXCOUNT key min maxCalculate the number of members in a specified dictionary interval in an ordered set
7 [ZRANGE key start stop WITHSCORES]Returns the members in the specified interval of an ordered set through index intervals
8 [ZRANGEBYLEX key min max LIMIT offset count]Returns the members of an ordered set through dictionary intervals
9 [ZRANGEBYSCORE key min max WITHSCORES] [LIMIT]Returns the members in the specified interval of an ordered set through fractions
10 ZRANK key memberReturns the index of a specified member in an ordered collection
11 [ZREM key member member …]Remove one or more members from an ordered collection
12 ZREMRANGEBYLEX key min maxRemoves all members of a given dictionary interval in an ordered set
13 ZREMRANGEBYRANK key start stopRemove all members of a given ranking range in an ordered set
14 ZREMRANGEBYSCORE key min maxRemove all members of a given fractional interval in an ordered set
15 [ZREVRANGE key start stop WITHSCORES]Returns the members of a specified interval in an ordered set. The score is from high to low through the index
16 [ZREVRANGEBYSCORE key max min WITHSCORES]Returns the members of a specified score range in an ordered set, and the scores are sorted from high to low
17 ZREVRANK key memberReturns the rank of a specified member in an ordered set. The members of an ordered set are sorted in descending order (from large to small)
18 ZSCORE key memberReturns the fractional value of a member in an ordered set
19 [ZUNIONSTORE destination numkeys key key …]The union of one or more ordered sets is calculated and stored in a new key
20 [ZSCAN key cursor MATCH pattern] [COUNT count]Iterate elements in ordered sets (including element members and element scores)

Application scenarios of various data types

type brief introduction characteristic scene
String (string) Binary security It can contain any data, such as JPG images or serialized objects. A key can store up to 512M
Hash (Dictionary) The set of key value pairs, that is, the map type in programming language It is suitable for storing objects and can modify only one property value just like updating an attribute in the database (in memcached, the whole string needs to be taken out and deserialized into an object, and then serialized and saved back after modification) Store, read and modify user attributes
List Double linked list Add and delete fast, provide an API to operate a certain element 1. The latest message ranking and other functions (such as the timeline of the circle of friends) 2. Message queue
Set (set) Hash table implementation, elements do not repeat 1. The complexity of adding, deleting and searching is O (1) 2. It provides operations such as intersection, union and subtraction for sets 1. Common friends 2. Use the uniqueness to count all the independent IP addresses visiting the website. 3. When friends recommend, find the intersection according to the tag. If it is greater than a certain threshold, it can be recommended
Sorted set Add a weight parameter score to the elements in the set, and the elements are arranged in order according to the score When the data is inserted into the collection, it is already sorted naturally

Redis command

The redis command is used to perform operations on the redis service.

To execute commands on the redis service, you need a redis client. The redis client is in the redis installation package we downloaded earlier.

grammar

The basic syntax of redis client is as follows:

$ redis-cli

example

The following example explains how to start the redis client:

Start the redis server, open the terminal and enter the commandredis-cliThe command will connect to the local redis service.

$ redis-cli
redis 127.0.0.1:6379>
redis 127.0.0.1:6379> PING

PONG

In the above example, we connect to the local redis service and execute thePINGCommand, which is used to detect whether the redis service is started.


Executing commands on remote services

If you need to execute commands on the remote redis service, we also use the sameredis-cliCommand.

grammar

$ redis-cli -h host -p port -a password

example

The following example shows how to connect to the redis service with host 127.0.0.1, port 6379, and password mypass.

$redis-cli -h 127.0.0.1 -p 6379 -a "mypass"
redis 127.0.0.1:6379>
redis 127.0.0.1:6379> PING

PONG

Redis key

The redis key command is used to manage the keys of redis.

grammar

The basic syntax of the redis key command is as follows:

redis 127.0.0.1:6379> COMMAND KEY_NAME

example

redis 127.0.0.1:6379> SET runoobkey redis
OK
redis 127.0.0.1:6379> DEL runoobkey
(integer) 1

In the above exampleDELIt’s an order,runoobkeyIt’s a key. If the key is deleted successfully, the command is output after execution(integer) 1Otherwise, the output will be output(integer) 0


Redis keys command

The following table gives the basic commands related to the redis key:

Serial number Command and description
1 DEL keyThis command is used to delete the key when it exists.
2 DUMP keySerializes the given key and returns the serialized value.
3 EXISTS keyCheck whether the given key exists.
4 EXPIRE keySeconds sets the expiration time, in seconds, for a given key.
5 EXPIREAT key timestampThe function of expireat is similar to that of exit, which is used to set the expiration time for the key. The difference is that the time parameter accepted by the exit command is UNIX timestamp.
6 PEXPIRE key millisecondsSet the expiration time of the key in milliseconds.
7 PEXPIREAT key milliseconds-timestampSet the UNIX timestamp of the key expiration time in milliseconds
8 KEYS patternFind all keys that match the given pattern.
9 MOVE key dbMove the key of the current database to the given database db.
10 PERSIST keyRemove the expiration time of the key, and the key will persist.
11 PTTL keyReturns the remaining expiration time of the key in milliseconds.
12 TTL keyReturns the TTL (time to live) of a given key in seconds.
13 RANDOMKEYReturns a key randomly from the current database.
14 RENAME key newkeyModify the name of key
15 RENAMENX key newkeyOnly if newkey does not exist, rename key to newkey.
16 [SCAN cursor MATCH pattern] [COUNT count]Iterate the database key in the database.
17 TYPE keyReturns the type of the value stored by the key.

Redis HyperLogLog

Redis added the hyperloglog structure in version 2.8.9.

Redis hyperloglog is an algorithm for cardinality statistics. The advantage of hyperloglog is that when the number or volume of input elements is very large, the space needed to calculate cardinality is always fixed and small.

In redis, each hyperloglog key only needs 12 KB of memory to calculate the cardinality of nearly 2 ^ 64 different elements. This is in sharp contrast to a collection where the more elements consume more memory when calculating cardinality.

However, because hyperloglog only calculates the cardinality based on the input elements and does not store the input elements themselves, hyperloglog cannot return the input elements like a collection.


What is cardinality?

For example, if the dataset {1, 3, 5, 7, 5, 7, 8}, then the cardinality set of this dataset is {1, 3, 5, 7, 8}, and the cardinality (non repeating elements) is 5. Cardinality estimation is to calculate cardinality quickly within the range of acceptable error.


example

The following example demonstrates the working process of hyperloglog:

redis 127.0.0.1:6379> PFADD runoobkey "redis"

1) (integer) 1

redis 127.0.0.1:6379> PFADD runoobkey "mongodb"

1) (integer) 1

redis 127.0.0.1:6379> PFADD runoobkey "mysql"

1) (integer) 1

redis 127.0.0.1:6379> PFCOUNT runoobkey

(integer) 3

Redis hyperloglog command

The following table lists the basic commands of redis hyperloglog:

Serial number Command and description
1 [PFADD key element element …]Add the specified element to hyperloglog.
2 [PFCOUNT key key …]Returns the cardinality estimate of the given hyperloglog.
3 [PFMERGE destkey sourcekey sourcekey …]Merge multiple hyperloglogs into one hyperloglog

Redis publish subscribe

Redis publish subscribe (Pub / sub) is a message communication mode: the sender (PUB) sends the message and the subscriber (sub) receives the message.

Redis clients can subscribe to any number of channels.

The following figure shows the relationship between channel 1 and the three clients that subscribe to the channel — client2, client5, and client1

When a new message is sent to channel 1 through the publish command, the message is sent to the three clients that subscribe to it:


example

The following example demonstrates how publish and subscribe works. Two redis cli clients need to be opened.

In our example, we created a subscription channel calledrunoobChat:

The first redis cli client

redis 127.0.0.1:6379> SUBSCRIBE runoobChat

Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "redisChat"
3)(integer) 1

Now, let’s re open a redis client, and then publish the message twice on the same channel runoobchat, and the subscriber can receive the message.

The second redis cli client

redis 127.0.0.1:6379> PUBLISH runoobChat "Redis PUBLISH test"

(integer) 1

redis 127.0.0.1:6379> PUBLISH runoobChat "Learn redis by runoob.com"

(integer) 1

\#The subscriber's client will display the following message
 1) "message"
2) "runoobChat"
3) "Redis PUBLISH test"
 1) "message"
2) "runoobChat"
3) "Learn redis by runoob.com"
  • Open the local redis service and two redis cli clients.
  • stayThe first redis cli clientinputSUBSCRIBE runoobChat, which means subscriptionrunoobChatChannel.
  • stayThe second redis cli clientinputPUBLISH runoobChat “Redis PUBLISH test”Send a message to the runoobchat channel. At this time, the first redis cli client will see the test message sent by the second redis cli client.

Redis publish subscribe command

The following table lists the common commands for redis publish and subscribe:

Serial number Command and description
1 [PSUBSCRIBE pattern pattern …]Subscribe to one or more channels that match the given pattern.
2 [PUBSUB subcommand argument [argument …]]View subscription and publishing system status.
3 PUBLISH channel messageSend information to the specified channel.
4 [PUNSUBSCRIBE pattern [pattern …]]Unsubscribe from all channels in the given mode.
5 [SUBSCRIBE channel channel …]Subscribe to information for a given channel or channels.
6 [UNSUBSCRIBE channel [channel …]]Unsubscribe from a given channel.

Redis transaction

Redis transaction can execute multiple commands at a time, and has the following three important guarantees:

  • Batch operations are put into the queue cache before the exec command is sent.
  • After receiving the exec command, it enters into the transaction execution. Any command in the transaction fails to execute, and the remaining commands are still executed.
  • During transaction execution, the command requests submitted by other clients are not inserted into the transaction execution command sequence.

A transaction will go through the following three stages from the beginning to the execution:

  • Transaction begins.
  • Order in.
  • Execute the transaction.

example

Here is an example of a transaction, which starts withMULTIStart a transaction, then queue multiple commands into the transaction, and finallyEXECThe command triggers the transaction and executes all commands in the transaction simultaneously

redis 127.0.0.1:6379> MULTI
OK

redis 127.0.0.1:6379> SET book-name "Mastering C++ in 21 days"
QUEUED

redis 127.0.0.1:6379> GET book-name
QUEUED

redis 127.0.0.1:6379> SADD tag "C++" "Programming" "Mastering Series"
QUEUED

redis 127.0.0.1:6379> SMEMBERS tag
QUEUED

redis 127.0.0.1:6379> EXEC
1) OK
2) "Mastering C++ in 21 days"
3) (integer) 3
4) 1) "Mastering Series"
   2) "C++"
   3) "Programming"

The execution of a single redis command is atomic, but redis does not add any mechanism to maintain atomicity on the transaction, so the execution of redis transaction is not atomic.

However, a batch instruction that has not been rolled back will not result in a batch operation.

This is the description on the official websitetransactions:

It’s important to note that even when a command fails, all the other commands in the queue are processed – Redis will not stop the processing of commands.

For example:

redis 127.0.0.1:7000> multi
OK
redis 127.0.0.1:7000> set a aaa
QUEUED
redis 127.0.0.1:7000> set b bbb
QUEUED
redis 127.0.0.1:7000> set c ccc
QUEUED
redis 127.0.0.1:7000> exec
1) OK
2) OK
3) OK

If it fails at set B BBB, set a has succeeded and will not be rolled back. Set C will continue to execute.


Redis transaction command

The following table lists the commands related to redis transactions:

Serial number Command and description
1 DISCARDCancels the transaction and discards the execution of all commands in the transaction block.
2 EXECExecute all commands within the transaction block.
3 MULTIMarks the beginning of a transaction block.
4 UNWATCHCancel the watch command from monitoring all keys.
5 [WATCH key key …]Monitor one (or more) key. If this (or these) key is changed by other commands before the transaction is executed, the transaction will be interrupted.

Redis script

Redis scripts use Lua interpreter to execute scripts. Redis 2.6 supports Lua environment through embedded. Common commands for executing scripts areEVAL

grammar

The basic syntax of the eval command is as follows:

redis 127.0.0.1:6379> EVAL script numkeys key [key ...] arg [arg ...]

example

The following example demonstrates the working process of redis script:

redis 127.0.0.1:6379> EVAL "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}" 2 key1 key2 first second

1) "key1"
2) "key2"
3) "first"
4) "second"

Redis script command

The following table lists the common commands of redis script:

Serial number Command and description
1 [EVAL script numkeys key key …] arg [arg …]Execute Lua script.
2 [EVALSHA sha1 numkeys key key …] arg [arg …]Execute Lua script.
3 [SCRIPT EXISTS script script …]Check whether the specified script has been saved in the cache.
4 SCRIPT FLUSHRemove all scripts from the script cache.
5 SCRIPT KILLKill the Lua script that is currently running.
6 SCRIPT LOAD scriptAdds a script script to the script cache, but does not execute the script immediately.

Redis connection

The redis connection command is mainly used to connect to the redis service.

example

The following example demonstrates how the client can connect to the redis service through password verification and detect whether the service is running:

redis 127.0.0.1:6379> AUTH "password"
OK
redis 127.0.0.1:6379> PING
PONG

Redis connection command

The following table lists the basic commands for redis connection:

Serial number Command and description
1 AUTH passwordVerify that the password is correct
2 ECHO messagePrint string
3 PINGSee if the service is running
4 QUITClose current connection
5 SELECT indexSwitch to the specified database

Redis server

Redis server commands are mainly used to manage redis services.

example

The following example demonstrates how to obtain the statistics of redis server:

Redis 127.0.0.1:6379 > information

Server
redis_version:2.8.13
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:c2238b38b1edb0e2
redis_ Mode: independent
OS: Linux 3.5.0-48-general x86_ Sixty-four
arch_bits:64
multiplexing_api:epoll
gcc_version:4.7.2
process_id:3856
run_id:0e61abd297771de3fe812a3c21027732ac9f41fe
tcp_port:6379
uptime_in_seconds:11554
uptime_in_days:0
Time zone: 10
lru_clock:16651447
config_file:

Customer
connected_clients:1
client-longest_output_list:0
client-biggest_input_buf:0
blocked_clients:0

Memory
used_memory:589016
used_memory_human:575.21K
used_memory_rss:2461696
used_memory_peak:667312
used_memory_peak_human:651.67K
used_memory_lua:33792
mem_fragmentation_ratio:4.18
mem_allocator:jemalloc-3.6.0

Persistence
Load: 0
rdb_changes_since_last_save:3
rdb_bgsave_in_progress:0
rdb_last_save_time:1409158561
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:0
rdb_current_bgsave_time_sec:-1
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_ last_ bgrewrite_ Status: OK
aof_ last_ write_ Status: OK

Statistics
total_connections_received:24
total_commands_processed:294
Instantaneous_ops_per_sec:0
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
evicted_keys:0
keyspace_hits:41
keyspace_misses:82
pubsub_channels:0
pubsub_patterns:0
Latest_fork_usec:264

Copy
Role: Master
connected_slaves:0
master_repl_offset:0
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

CPU
used_cpu_sys:10.49
used_cpu_user:4.96
used_cpu_sys_children:0.00
used_cpu_user_children:0.01

Key space
db0:keys = 94,expires = 1,avg_ttl = 41638810
db1:keys = 1,expires = 0,avg_ttl = 0
db3:keys = 1,expires = 0,avg_ttl = 0

Redis server command

Relevant commands for announcing the listing of redis server:

Serial number Command and description
1 BGREWRITEAOFPerforms an AOF (attach file) file rewrite operation asynchronously
2 BGSAVEInitialize and save the data of the current database to the disk in the background
3 [CLIENT KILL ip:port] [ID client-id]Close client connection
4 Client listGets a list of client connections to the server
5 CLIENT GETNAMEGets the name of the connection
6 Client pause timeoutStops running a command from the client at a specified time
7 CLIENT SETNAME connection-nameSets the name of the current connection
8 colonyslot Gets the cumulative binary mapping array
9 COMMANDGet redis command list
10 Command countGet the total number of redis commands
11 Command getkeysGets all the keys for the given command
12 TIMEReturns the current server time
13 [command info command namecommand-name …]Gets the array described by the specified redis command
14 CONFIG GET parameterGets the value of the specified configuration parameter
15 CONFIG REWRITEFor the redis.conf The configuration file is rewritten
16 Config set parameter valueModify redis configuration parameters without restarting
17 CONFIG RESETSTATReset some statistics in the info command
18 years old DBSIZEReturns the number of keys in the current database
19 Debug object keyGet debug information for the key
20 DEBUG SEGFAULTLet redis service crash
21 FLUSHALLRemove all keys from all databases
22 FLUSHDBDelete all keys for the current database
23 [INFO section]Get all kinds of information and statistics of redis server
24 LASTSAVEReturns the time when redis successfully saved the data to the disk, in UNIX format
25 MONITORPrint out the command received by redis server in real time, and test it
26 ROLEReturns the role of the master-slave instance
27 SAVESave data to hard disk synchronously
28 [SHUTDOWN NOSAVE] [SAVE]Initialize saving data to the hard disk and shut down the server
29 Slaveof host portConverts the current server to a secondary server of the specified server (secondary server)
30 [slowlog subcommandParameters]Manage the slow log of redis
31 SYNCInternal command for copy function (copy)

Redis Stream

Redis stream is a new data structure added to redis 5.0.

Redis stream is mainly used for message queuing (MQ, message queue). Redis itself has a redis publish / subscribe (Pub / sub) to realize the function of message queuing. However, it has a disadvantage that messages cannot be persistent. In case of network disconnection and redis downtime, messages will be discarded.

In short, publish subscribe (Pub / sub) can distribute messages, but cannot log historical messages.

Redis stream provides message persistence and master-slave replication functions, enabling any client to access data at any time, and can remember the access location of each client, and can ensure that messages are not lost.

The structure of redis stream is shown as follows. It has a message linked list to string all the messages added. Each message has a unique ID and corresponding content

Each stream has a unique name, which is the key of redis. It is automatically created when we first use the xadd instruction to append messages.

Analysis of the above figure:

  • Consumer Group: consumption group, which is created by using the xgroup create command. A consumption group has multiple consumers.
  • last_delivered_id: cursor, each consumer group will have a cursor last_ delivered_ ID, any consumer reading the message will make the cursor last_ delivered_ ID moves forward.
  • pending_ids: the state variable of the consumer, which is used to maintain the unidentified ID of the consumer. pending_ IDS records messages that are currently read by the client, but there is no ack (acknowledgement character).

Message queuing related commands:

  • XADD-Add message to end
  • XTRIM-Stream pruning to limit length
  • XDEL-Delete message
  • XLEN-Gets the number of elements contained in the stream, that is, the message length
  • XRANGE-Get the message list and automatically filter the deleted messages
  • XREVRANGE-Reverse access message list, ID from large to small
  • XREAD-Get message list in blocking or non blocking way

Consumer group command:

  • XGROUP CREATE-Create consumer group
  • XREADGROUP GROUP-Read messages from consumer groups
  • XACK-Mark message as processed
  • XGROUP SETID-Set a new last delivery message ID for the consumer group
  • XGROUP DELCONSUMER-Delete consumer
  • XGROUP DESTROY-Delete consumer group
  • XPENDING-Displays information about pending messages
  • XCLAIM-Transfer ownership of messages
  • XINFO-View information about streams and consumer groups;
  • XINFO GROUPS-Print consumer group information;
  • XINFO STREAM-Print stream information

XADD

Use xadd to add messages to the queue. If the specified queue does not exist, a queue will be created. Xadd syntax format:

XADD key ID field value [field value ...]
  • key: the name of the queue, which is created if it does not exist
  • ID: message ID, we use * to indicate that it is generated by redis. It can be customized, but the incremental character should be guaranteed by ourselves.
  • field value: record.

example

redis**>** XADD mystream ***** name Sara surname OConnor
"1601372323627-0"
redis**>** XADD mystream ***** field1 value1 field2 value2 field3 value3
"1601372323627-1"
redis**>** XLEN mystream
**(**integer**)** 2
redis**>** XRANGE mystream - +
1**)** 1**)** "1601372323627-0"
  2**)** 1**)** "name"
   2**)** "Sara"
   3**)** "surname"
   4**)** "OConnor"
2**)** 1**)** "1601372323627-1"
  2**)** 1**)** "field1"
   2**)** "value1"
   3**)** "field2"
   4**)** "value2"
   5**)** "field3"
   6**)** "value3"
redis**>**

XTRIM

Use xtrim stream to trim, limit the length, syntax format:

XTRIM key MAXLEN [~] count
  • key: queue name
  • MAXLEN: length
  • count: quantity

example

127.0.0.1:6379**>** XADD mystream ***** field1 A field2 B field3 C field4 D
"1601372434568-0"
127.0.0.1:6379**>** XTRIM mystream MAXLEN 2
**(**integer**)** 0
127.0.0.1:6379**>** XRANGE mystream - +
1**)** 1**)** "1601372434568-0"
  2**)** 1**)** "field1"
   2**)** "A"
   3**)** "field2"
   4**)** "B"
   5**)** "field3"
   6**)** "C"
   7**)** "field4"
   8**)** "D"
127.0.0.1:6379**>**

redis**>**

XDEL

Use xdel to delete the message. Syntax format:

XDEL key ID [ID ...]
  • key: queue name
  • ID: message ID

Use xdel to delete the message. Syntax format:

XLEN

Use xlen to get the number of elements contained in the flow, i.e. message length. Syntax format:

XLEN key
  • key: queue name

example

redis**>** XADD mystream ***** item 1
"1601372563177-0"
redis**>** XADD mystream ***** item 2
"1601372563178-0"
redis**>** XADD mystream ***** item 3
"1601372563178-1"
redis**>** XLEN mystream
**(**integer**)** 3
redis**>**

XRANGE

Using xrange to get the message list will automatically filter the deleted messages. Syntax format:

XRANGE key start end [COUNT count]
  • key: queue name
  • start: start value,Represents the minimum value
  • end: end value,+Represents the maximum value
  • count: quantity

example

redis**>** XADD writers ***** name Virginia surname Woolf
"1601372577811-0"
redis**>** XADD writers ***** name Jane surname Austen
"1601372577811-1"
redis**>** XADD writers ***** name Toni surname Morrison
"1601372577811-2"
redis**>** XADD writers ***** name Agatha surname Christie
"1601372577812-0"
redis**>** XADD writers ***** name Ngozi surname Adichie
"1601372577812-1"
redis**>** XLEN writers
**(**integer**)** 5
redis**>** XRANGE writers - + COUNT 2
1**)** 1**)** "1601372577811-0"
  2**)** 1**)** "name"
   2**)** "Virginia"
   3**)** "surname"
   4**)** "Woolf"
2**)** 1**)** "1601372577811-1"
  2**)** 1**)** "name"
   2**)** "Jane"
   3**)** "surname"
   4**)** "Austen"
redis**>**

XREVRANGE

Using xrevrange to get the message list will automatically filter the deleted messages. Syntax format:

XREVRANGE key end start [COUNT count]
  • key: queue name
  • end: end value,+Represents the maximum value
  • start: start value,Represents the minimum value
  • count: quantity

example

redis**>** XADD writers ***** name Virginia surname Woolf
"1601372731458-0"
redis**>** XADD writers ***** name Jane surname Austen
"1601372731459-0"
redis**>** XADD writers ***** name Toni surname Morrison
"1601372731459-1"
redis**>** XADD writers ***** name Agatha surname Christie
"1601372731459-2"
redis**>** XADD writers ***** name Ngozi surname Adichie
"1601372731459-3"
redis**>** XLEN writers
**(**integer**)** 5
redis**>** XREVRANGE writers + - COUNT 1
1**)** 1**)** "1601372731459-3"
  2**)** 1**)** "name"
   2**)** "Ngozi"
   3**)** "surname"
   4**)** "Adichie"
redis**>**

XREAD

Use xread to get the message list in blocking or non blocking mode. Syntax format:

XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] id [id ...]
  • count: quantity
  • milliseconds: optional, blocking milliseconds. If it is not set, it means non blocking mode
  • key: queue name
  • id: message ID

example

*#Read two messages from the stream header*
**>** XREAD COUNT 2 STREAMS mystream writers 0-0 0-0
1**)** 1**)** "mystream"
  2**)** 1**)** 1**)** 1526984818136-0
     2**)** 1**)** "duration"
      2**)** "1532"
      3**)** "event-id"
      4**)** "5"
      5**)** "user-id"
      6**)** "7782813"
   2**)** 1**)** 1526999352406-0
     2**)** 1**)** "duration"
      2**)** "812"
      3**)** "event-id"
      4**)** "9"
      5**)** "user-id"
      6**)** "388234"
2**)** 1**)** "writers"
  2**)** 1**)** 1**)** 1526985676425-0
     2**)** 1**)** "name"
      2**)** "Virginia"
      3**)** "surname"
      4**)** "Woolf"
   2**)** 1**)** 1526985685298-0
     2**)** 1**)** "name"
      2**)** "Jane"
      3**)** "surname"
      4**)** "Austen"

XGROUP CREATE

Use xgroup create to create a consumer group. Syntax format:

XGROUP [CREATE key groupname id-or-$] [SETID key groupname id-or-$] [DESTROY key groupname] [DELCONSUMER key groupname consumername]
  • key: the name of the queue, which is created if it does not exist
  • groupname: group name.
  • $: indicates that consumption starts from the tail, only new messages are accepted, and all current stream messages are ignored.

Start from scratch:

XGROUP CREATE mystream consumer-group-name 0-0

Starting from the tail:

XGROUP CREATE mystream consumer-group-name $

XREADGROUP GROUP

Use xreadgroup group to read the messages in the consumption group. Syntax format:

XREADGROUP GROUP group consumer [COUNT count] [BLOCK milliseconds] [NOACK] STREAMS key [key ...] ID [ID ...]
  • group: consumer group name
  • consumer: consumer name.
  • count: number of reads.
  • milliseconds: number of milliseconds blocked.
  • key: queue name.
  • IDID: message.