This article, as a general knowledge course of Redis, aims to give you a conceptual and holistic understanding of Redis, and you can get started quickly to lay a foundation for in-depth Redis.
Article Summary:
- The introduction of Redis
- Redis compared to other databases
- Redis compares with other caching implementations
- Redis data structure type
- The Redis command operates on several data types
- Spring Data Redis operates on several Data types
- Zsets (ordered sets) guarantee order
- A SET randomly retrieves elements
The introduction of Redis
Redis is a non-relational database (NOSQL for short).
Redis is a remote in-memory database that a Redis client can request from a server over TCP.
Redis is robust and supports persistence and replication, making it easy to store and read massive amounts of data.
So just how fast is Redis? Redis comes with a tool called Redis-benchmark to simulate N clients making M requests at the same time. You can use redis-benchmark-h to check parameters.
The performance of the SET and GET operations was tested one million times:
$ redis-benchmark -n 1000000 -t setThe get - 16 P - q
SET: 198098.27 requests per second
GET: 351988.72 requests per second
Copy the code
Redis compared to other databases
It’s easy to “miss the forest for the trees” or “the hammer in your hand makes everything look like a nail.”
Therefore, we first do a horizontal comparison with common database systems in the market, so that you can get a more intuitive sense of Redis characteristics.
Redis compares with other caching implementations
At the same time Redis as a common cache implementation, we also compare the advantages and disadvantages of common cache implementation.
Redis data type
Before Redis 5 introduced a new Stream data type, Redis could store mappings between keys and five different data structure types. The five data structure types are STRING, LIST, SET, HASH, and ZSET.
An overview of Redis’s five data types
Serial number | Structure type | Structure to store values | Structure literacy |
---|---|---|---|
1 | STRING | String, integer, floating point | Perform an operation on the entire string or part of a string; Perform increment or Decrement on integers and floating-point numbers |
2 | LIST | A linked list in which each node contains a string | Push and pop elements from both ends of the list (queue operations); Trim the list according to the offset; Read single or multiple elements; Find or remove elements by value |
3 | SET | An unordered collection that contains strings and is not repeatable | Add, get, and remove individual elements Checks if an element exists in the collection; Calculate intersection, union and difference sets; Retrieves elements randomly from the collection |
4 | HASH | An unordered hash table containing key-value pairs | Add, get, and remove single key-value pairs; Get all key values |
5 | ZSET | An ordered mapping between a string member and a floating-point score. The order of elements is determined by the size of the score | Add, get, and delete individual elements; Retrieves elements based on a range or member |
The Redis command operates on five data types
STRING command
String manipulation
For strings, Redis supports the most basic SET GET and DEL operations. It also supports many complex operations, which are briefly described below.
Serial number | The command | describe |
---|---|---|
1 | SET key value | Sets the value of the specified key |
2 | GET key | Gets the value of the specified key |
3 | DEL key | Delete this key and its value. This command works for all five data types |
4 | GETRANGE key start end | Returns a subcharacter of the string value in key |
5 | SETRANGE key offset value | Overwrites the string value stored for the given key with the value argument, starting at offset |
6 | STRLEN key | Returns the length of the string value stored by key |
Here’s a quick demonstration of how Command operates on strings:
127.0.0.1:6379> GET key-string
(nil)
127.0.0.1:6379> SET key-str "my string value"OK 127.0.0.1:6379 > GET key - STR"my string value"127.0.0.1:6379 > DEL key - STR (integer) 1
127.0.0.1:6379> GET key-str
(nil)
127.0.0.1:6379>
Copy the code
SETEX and SETNX
SETEX and SETNX are useful for distributed locking.
Serial number | The command | describe |
---|---|---|
1 | SETEX key seconds value | Associate the value value with the key and set the expiration time of the key to seconds in seconds |
2 | SETNX key value | Set the key value only if the key does not exist |
Here’s an example of a SETEX application:
When a distributed session is implemented, a specified expiration time is set when the user logs in. Each time a user requests an interface, the expiration time is reset. A distributed session is invalidated when no interface is invoked within a specified period of time.
Digital operation
The following operations are supported for numbers:
Serial number | The command | describe |
---|---|---|
1 | INCR key | Increment the value of the number stored in the key by one |
2 | INCRBY key increment | Add the value stored in the key to the given increment |
3 | INCRBYFLOAT key increment | Add the value stored by key to the given floating point increment |
4 | DECR key | Subtract the number stored in the key by one |
5 | DECRBY key decrement | Values stored by key minus the given decrement value |
Here is a brief demonstration of Command:
127.0.0.1:6379> SET key-num 0
OK
127.0.0.1:6379> INCR key-num
(integer) 1
127.0.0.1:6379> GET key-num
"1"127.0.0.1:6379 > INCR key - num (integer) 2
127.0.0.1:6379> GET key-num
"2"127.0.0.1:6379 > INCR key - num (integer) 3
127.0.0.1:6379> GET key-num
"3"
127.0.0.1:6379> INCRBY key-num 100
(integer) 103
127.0.0.1:6379> GET key-num
"103"
127.0.0.1:6379> INCRBY key-num 100
(integer) 203
127.0.0.1:6379> DECR key-num
(integer) 202
127.0.0.1:6379> DECRBY key-num 100
(integer) 102
127.0.0.1:6379> DECRBY key-num 100
(integer) 2
127.0.0.1:6379> DECRBY key-num 100
(integer) - 98.Copy the code
The batch operation
Serial number | The command | describe |
---|---|---|
1 | MGET key1 [key2..] | Gets the values of all (one or more) of the given keys |
2 | MSET key value [key value …] | Set one or more key-value pairs at the same time |
3 | MSETNX key value [key value …] | Sets one or more key-value pairs simultaneously if and only if none of the given keys exist |
127.0.0.1:6379> MSET a 1 b 2 c 3
OK
127.0.0.1:6379> MGET a b c
1) "1"
2) "2"
3) "3"127.0.0.1:6379> MSETNX a 1 b 2 c 3integer0 127.0.1:6379 > MSETNX a 1 b 2 d 4 (integer) 0 127.0.1:6379 > MSETNX d 4 e 5 (integer6379 > 1 127.0.0.1) :Copy the code
BIT operation
Serial number | The command | describe |
---|---|---|
1 | GETBIT key offset | Returns the bit at the specified offset for the string value stored by key. |
2 | SETBIT key offset value | Sets or clears the bits at the specified offset for the string value held by key. |
3 | BITCOUNT key [start] [end] | Evaluates the set bits in the string |
4 | BITOP operation destkey key [key …] | Bit-to-bit operations are performed between multiple keys (containing string values) and the results are stored in the target key. |
The LIST command
One of the unique features of Redis is that it supports a linked list structure. The following are the operation commands for the linked list structure. It is important to be familiar with these commands to master the Redis linked list structure.
Serial number | The command | describe |
---|---|---|
1 | BLPOP key1 [key2 ] timeout | Removes and retrieves the first element of the list. If there are no elements in the list, the list is blocked until the wait times out or an eject element is found. |
2 | BRPOP key1 [key2 ] timeout | Removes and retrieves the last element of the list. If there are no elements in the list, the list is blocked until the wait times out or an eject element is found. |
3 | BRPOPLPUSH source destination timeout | Pops a value from a list, inserts the pop-up element into another list and returns it; If the list has no elements, it blocks until the wait times out or a popup element is found. |
4 | LINDEX key index | Gets the elements in the list by index |
5 | LINSERT key BEFORE | AFTER pivot value |
6 | LLEN key | Get the list length |
7 | LPOP key | Removes and gets the first element of the list |
8 | LPUSH key value1 [value2] | Inserts one or more values into the list header |
9 | LPUSHX key value | Inserts a value into the head of an existing list |
10 | LRANGE key start stop | Gets the elements in the specified range of the list |
11 | LREM key count value | Remove list elements |
12 | LSET key index value | Set the value of a list element by index |
13 | LTRIM key start stop | To trim a list, that is, to keep only elements within a specified range, and to remove all elements that are not within a specified range. |
14 | RPOP key | The removed element is returned except for the last element in the list. |
15 | RPOPLPUSH source destination | Removes the last element of the list and adds it to another list and returns |
16 | RPUSH key value1 [value2] | Adds one or more values to the list |
17 | RPUSHX key value | Add a value to an existing list |
127.0.0.1:6379> LPUSH list1 1
(integer) 1
127.0.0.1:6379> RPOP list1
"1"
127.0.0.1:6379> RPOP list1
(nil)
127.0.0.1:6379> BRPOP list1 10
(nil)
(10.10s)
127.0.0.1:6379>
127.0.0.1:6379> LPUSH list1 1 2 3 4 5
(integer) 5
127.0.0.1:6379> LSET list1 4 50
OK
127.0.0.1:6379> LSET list1 5 50
(error) ERR index out of range
Copy the code
BLPOP BRPOP BRPOPLPUSH is blocking and is usually used in message queues.
The SET command
Redis’ Set is an unordered collection of type String. Collection members are unique, which means that no duplicate data can occur in the collection.
The collection in Redis is realized by hash table, so the complexity of adding, deleting and searching is O(1).
Redis limits each key to 512 MEgabytes of data, and the maximum number of members in a collection is 232-1 (4294967295, each collection can store more than 4 billion members).
Serial number | The command | describe |
---|---|---|
1 | SADD key member1 [member2] | Adds one or more members to a collection |
2 | SCARD key | Gets the number of members of the collection |
3 | SDIFF key1 [key2] | Returns the difference set of all sets given |
4 | SDIFFSTORE destination key1 [key2] | Returns the difference set for a given collection and stores it in destination |
5 | SINTER key1 [key2] | Returns the intersection of all sets given |
6 | SINTERSTORE destination key1 [key2] | Returns the intersection of all the given collections and stores them in destination |
7 | SISMEMBER key member | Check whether the member element is a member of the collection key |
8 | SMEMBERS key | Returns all members of the collection |
9 | SMOVE source destination member | Move the member element from the source collection to the Destination collection |
10 | SPOP key | Removes 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] | Removes one or more members of a collection |
13 | SUNION key1 [key2] | Returns the union of all given sets |
14 | SUNIONSTORE destination key1 [key2] | The union of all given collections is stored in the Destination collection |
15 | SSCAN key cursor [MATCH pattern] [COUNT count] | Iterate over the elements in the collection |
127.0.0.1:6379 > SADDset1 a b c d e
(integer) 127.0.0.1:6379 > SCARDset
(integer) 0 127.0.0.1:6379 > SCARDset1
(integer) 127.0.0.1:6379 > SISMEMBERset1 f
(integer) 0 127.0.0.1:6379 > SISMEMBERset1 e
(integer127.0.0.1) 1:6379 > SMEMBERSset1, 1)"d"
2) "c"
3) "a"
4) "b"
5) "e"127.0.0.1:6379 > SPOPset1
"d"127.0.0.1:6379 > SPOPset1
"a"127.0.0.1:6379 > SMOVEset1 set2 b
(integer127.0.0.1) 1:6379 > SMOVEset1 set2 c
(integer127.0.0.1) 1:6379 > SMEMBERSset2 (1)"b"
2) "c"
Copy the code
SPOP, due to its randomness, can be used as a base implementation for business scenarios such as lottery programs.
HASH commands
Redis Hash is a mapping table of fields and values of string type. Similar to the Map structure in the Java language, Hash is especially suitable for storing objects.
Serial number | The command | describe |
---|---|---|
1 | HDEL key field1 [field2] | Deletes one or more hash table fields |
2 | HEXISTS key field | Check whether the specified field in the hash table key exists |
3 | HGET key field | Gets the value of the specified field stored in the hash table |
4 | HGETALL key | Gets all the fields and values of the specified key in the hash table |
5 | HINCRBY key field increment | Add increment to the integer value of the specified field in the hash table key |
6 | HINCRBYFLOAT key field increment | Increments the floating point value of the specified field in the hash table key |
7 | HKEYS key | Gets all fields in the hash table |
8 | HLEN key | Gets the number of fields in the hash table |
9 | HMGET key field1 [field2] | Gets the values of all given fields |
10 | HMSET key field1 value1 [field2 value2 ] | Set multiple field-value pairs into the hash key at the same time |
11 | HSET key field value | Set the value of field in hash table key to value |
12 | HSETNX key field value | Set the value of the hash table field only if the field field does not exist. |
13 | HVALS key | Gets all values in the hash table |
14 | HSCAN key cursor [MATCH pattern] [COUNT count] | Iterates key-value pairs in a hash table. |
127.0.0.1:6379 > HSET User001 name"Tom"
(integer) 1
127.0.0.1:6379> HSET User001 birthday "1990-01-20"
(integer) 1
127.0.0.1:6379> HSET User001 gender "Man"
(integer) 1
127.0.0.1:6379> HKEYS User001
1) "name"
2) "birthday"
3) "gender"127.0.0.1:6379 > HGETALL User001 1)"name"
2) "Tom"
3) "birthday"
4) "1990-01-20"
5) "gender"
6) "Man"
Copy the code
ZSET command
Ordered collections, like hashes, are used to store key-value pairs. The keys of an ordered set are called members, and each member is different; The value of an ordered set is called a score, and the score must be a floating point number.
Serial number | The command | describe |
---|---|---|
1 | ZADD key score1 member1 [score2 member2] | Adds one or more members to an ordered collection, or updates the scores of existing members |
2 | ZCARD key | Gets the number of members of an ordered collection |
3 | ZCOUNT key min max | Computes the number of members in an ordered set with a specified interval fraction |
4 | ZINCRBY key increment member | Increment the score of a specified member in an ordered set |
5 | ZINTERSTORE destination numkeys key [key …] | Computes the intersection of one or more ordered sets given and stores the result set in a new ordered set key |
6 | ZLEXCOUNT key min max | Computes the number of members in the specified dictionary range in an ordered collection |
7 | ZRANGE key start stop [WITHSCORES] | Returns an ordered collection of the members of a specified interval through an indexed interval |
8 | ZRANGEBYLEX key min max [LIMIT offset count] | Returns a member of an ordered collection through a dictionary interval |
9 | ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT] | Returns an ordered set of members within a specified interval by a fraction |
10 | ZRANK key member | Returns the index of the specified member in the ordered collection |
11 | ZREM key member [member …] | Removes one or more members of an ordered collection |
12 | ZREMRANGEBYLEX key min max | Removes all members of the given dictionary range from the ordered collection |
13 | ZREMRANGEBYRANK key start stop | Removes all members of the given rank range from the ordered collection |
14 | ZREMRANGEBYSCORE key min max | Removes all members of the given fractional interval from the ordered set |
15 | ZREVRANGE key start stop [WITHSCORES] | Returns the members of an ordered set in a specified interval, indexed from high to bottom |
16 | ZREVRANGEBYSCORE key max min [WITHSCORES] | Returns the members of the ordered set within the specified range of scores, sorted from highest to lowest |
17 | ZREVRANK key member | Returns the ranking of the specified members of an ordered set, ordered in decreasing order (from largest to smallest) by score value |
18 | ZSCORE key member | Returns the score value of a member in an ordered set |
19 | ZUNIONSTORE destination numkeys key [key …] | Computes the union of a given one or more ordered sets and stores it in a new key |
20 | ZSCAN key cursor [MATCH pattern] [COUNT count] | Iterating over elements in an ordered set (including element members and element scores) |
127.0.0.1:6379> ZADD Users 1 zhangsan 2 lisi 3 wangwu 4 maliu
(integer) 4
127.0.0.1:6379> ZCARD Users
(integer) 4
127.0.0.1:6379> ZRANK Users maliu
(integer) 3
127.0.0.1:6379> ZSCAN Users 0
1) "0"
2) 1) "zhangsan"
2) "1"
3) "lisi"
4) "2"
5) "wangwu"
6) "3"
7) "maliu"
8) "4"127.0.0.1:6379 >Copy the code
conclusion
This article introduces you to Redis, and gives you a comprehensive understanding of Redis features and functions through horizontal comparison. Then we introduce five basic data structures of Redis in turn, and the commands to operate it. As an introduction to Redis, this article aims to give you a conceptual and holistic understanding of Redis and lay the foundation for further study of Redis.
Today, I only take you to understand the tip of the iceberg of Redis knowledge graph. I hope that with our joint efforts, we can constantly improve our skill graph and build our knowledge system together, so as to be proud in this era of algorithm and intelligence.
A link to the
The author resources
- Use of Redis pipeline technology
- Java Cache analysis
The resources
-
Redis Benchmarks
-
Redis Tutorial