1. Install Redis

Redis6.0 was released in 2020, so we installed Redis3.0. 😂

1.1. Install Redis on Linux

We install Redis on CentOS. There are three common installation methods:

  • Yum/APT software management software installation
  • Source code for installation
  • Containerized installation

Here we choose the second option:

  • 1) Download the Redis source code zip package to the current directory
Wget HTTP: / / http://download.redis.io/releases/redis-3.0.7.tar.gzCopy the code
  • 2) Unzip the Redis source code package
The tar XZF redis - 3.0.7. Tar. GzCopy the code
  • 3) Establish a soft connection to the redis directory pointing to Redis-3.0.7
Ln -s redis - 3.0.7 redisCopy the code
  • 4) Access the Redis directory
 cd redis
Copy the code
  • 5) Compile (make sure you have GCC installed on your operating system before compiling)
 make
Copy the code
  • 6) the installation
make install
Copy the code

You can run redis-cli -v to view the redis version

1.2. Start Redis

There are three ways to start Redis: default configuration, run configuration, and profile startup.

Here we start Redis with the default configuration:

redis-server
Copy the code

In the production environment, configuration files are usually used for startup.

1.3 Redis command line client

The Redis service has been started and is now connected using Redis – CLI.

Redis -cli -h 127.0.0.1 -p 6379Copy the code

2. Redis basic data structure

Redis has five basic data structures: string, list, set, Hash, and zset.

2.1. Strings

The string type is the most fundamental data structure of Redis. All keys are strings,

All data structures in Redis are named by a unique key string, which is then used to retrieve the corresponding value data. The difference between different types of data structures lies in the different structures of values.

And the other data structures are built on top of the string type, so the string type can lay the foundation for learning the other four data structures.

In addition to the simple strings described in the figure above, string values can also be complex strings (such as JSON, XML), numbers (integers, floating points), or even binary (images, audio, video), but cannot exceed 512MB.

2.1.1, commands,

  • Set the value
set key value [ex seconds] [px milliseconds] [nx|xx]
Copy the code

Set key-value pair (Hello, World) to OK

127.0.0.1:6379> set Hello World 
OK
Copy the code

The set command has several options:

  • Ex seconds: Sets the key expiration time in seconds.

  • Px milliseconds: Sets the expiration time for the key in milliseconds.

  • Nx: The key must not exist.

  • Xx: In contrast to nx, the key must exist for the update to be set successfully.

  • Get the value

get key
Copy the code

Get the value for the key Hello:

127.0.0.1:6379 > get the Hello World ""Copy the code

If the key to be retrieved does not exist, nil is returned:

127.0.0.1:6379 > get some (nil)Copy the code
  • Batch set value
mset key value [key value ...]
Copy the code

You can read and write multiple strings in batches, saving network time.

Set four key pairs at a time using the mset command:

127.0.0.1:6379> mset a 1 b 2 c 3 d 4 
OK
Copy the code
  • Batch fetch value
mget key [key ...] 
Copy the code

The following operation fetches the values of keys A, b, c, and d:

127.0.0.1:6379 > mget a b c d (1) "1" (2) "2" 3) "3" 4) "4"Copy the code
  • count
incr key 
Copy the code

The incr command is used to increment the value automatically. The returned result can be divided into three types:

  • Value is not an integer, error returned.

  • The value is an integer and returns the incremented result.

  • Key does not exist, increments to 0, returns 1.

127.0.0.1:6379>  set age 18
OK
127.0.0.1:6379> incr age
(integer) 19
Copy the code

In addition to incr commands, Redis provides DECr (decrement), incrby (decrby decrement), and incrByFloat (incrByFloat).

2.1.2 Application Scenarios

Strings are the most widely used data structure in Redis. Let’s take a look at some typical application scenarios in actual development.

2.1.2.1 cache function

The following figure shows a typical cache usage scenario, in which Redis serves as the cache layer and MySQL serves as the storage layer. Most of the requested data is obtained from Redis. Because Redis supports high concurrency, caching is often used to speed up reads and writes and reduce back-end stress.

2.1.2.2, counting

Many applications will use Redis as a basic tool for counting, it can achieve fast counting, query caching, and data can be asynchronously landed to other data sources. For example, keep track of how many times an article is read.

2.1.2.3 Sharing Session

Session sharing for distributed applications ensures that users can access all services after one login.

2.1.2.4 distributed Locking

Distributed lock can be realized by using setnx command. Due to the single-thread command processing mechanism of Redis, if multiple clients execute setnx key value at the same time, only one client can be successfully set according to the characteristics of setNx, so setnx can be used as an implementation scheme of distributed lock.

Here is the simplest Redis distributed lock implementation:

2.2, the hash

The Redis dictionary is similar to the Java language HashMap. In Redis, hash type refers to the key value itself is a key-value pair structure, such as value={{field1, value1},… {fieldN, valueN}}

2.2.1, commands,

  • Set the value
hset key field value
Copy the code

Add a pair of field-values for user: 1:

127.0.0.1:6379> hset user:1 name tom 
(integer) 1
Copy the code

Returns 1 on success, 0 on failure. In addition, Redis provides hsetnx commands, which are similar to set and setnx commands except that the scope is changed from key to field.

  • Get the value
hget key field 
Copy the code

Get the value for the name field (attribute) of user: 1:

127.0.0.1:6379> hget user:1 name 
"tom"
Copy the code
  • Delete the field
hdel key field [field ...]
Copy the code

Hdel deletes one or more fields and returns the number of fields successfully deleted, for example:

127.0.0.1:6379> hdel user:1 name 
(integer) 1 
127.0.0.1:6379> hdel user:1 age 
(integer) 0
Copy the code
  • Set or obtain field-values in batches
hmget key field [field ...]  hmset key field value [field value ...]Copy the code

Hmset and HMGET are used to set and obtain field-values in batches respectively. The parameters required by HMset are key and multiple field-values, and the parameters required by HMGET are key and multiple fields. Such as:

127.0.0.1:6379> hmset user:1 name mike age 12 city tianjin 
OK
127.0.0.1:6379> hmget user:1 name city 
1) "mike" 
2) "tianjin"
Copy the code

2.2.2 Application Scenarios

2.2.2.1 Store objects

The filed-value structure of hash is very suitable for storing objects. Field is used to store attribute names and value is used to store attribute values. Json serializers are also provided in some clients.

2.3 list,

Redis lists are similar to linkedLists in the Java language. Similarly, list inserts and deletes are very fast with O(1) time, but index positioning is slow with O(n) time.

So, similarly, lists can act as stacks and queues.

For example, inserts and pops at both ends of a list can simulate the operation of a stack:

The list type has two characteristics: first, the elements in the list are ordered, which means that you can retrieve an element or a list of elements within a range by indexing it. Second, elements in a list can be repeated.

2.3.1, commands,

There are five main types of operations on lists:

Operation type operation
add rpush lpush linsert
To find the lrange lindex llen
delete lpop rpop lren ltrim
Modify the lset
Blocking operations blpop brpop
  • Add operation

Insert elements from the right

rpush key value [value ...]
Copy the code

Insert elements C, b, a from right to left:

127.0.01:6379 > rpush listKey C b A (integer) 3Copy the code

The lrange0-1 command gets all the elements of the list from left to right:

127.0.0.1:6379> lrange listkey 0 -1 
1) "c" 
2) "b" 
3) "a"
Copy the code

Inserting elements from the left is similar and will not be repeated

  • Inserts elements before or after an element
linsert key before|after pivot value
Copy the code

The linsert command finds the element from the list equal to Pivot, and inserts a new element value before or after it. For example, the following operation inserts Java before element B in the list:

127.0.0.1:6379> linsert listkey before b java 
(integer) 4
Copy the code

The result is 4, representing the length of the current command, and the current list becomes:

127.0.0.1:6379> lrange listkey 0 -1 
1) "c" 
2) "java" 
3) "b" 
4) "a"
Copy the code
  • To find the

Gets a list of elements in the specified range

lrange key start end
Copy the code

The lrange operation retrieves all elements in the specified index range of the list.

For example, if you want to get elements 2 through 4 of a list:

127.0.0.1:6379> lrange listkey 1 3 
1) "java" 
2) "b" 
3) "a"
Copy the code

Gets the element at the specified index subscript of the list

lindex key index
Copy the code

For example, the last element of the current list is a:

127.0.0.1:6379> lindex listkey -1 
"a"
Copy the code

Get the list length

llen key
Copy the code

For example, the following example currently has a list length of 4:

127.0.0.1:6379> llen listkey 
(integer) 4
Copy the code
  • delete

Pops the element from the left side of the list

lpop key
Copy the code

From the right side of the list

rpop key
Copy the code

Delete the specified element

lrem key count value
Copy the code
  • Modify the
lset key index newValue
Copy the code
  • Blocking operations

Blocking pop-up is as follows:

blpop key [key ...]  timeout brpop key [key ...]  timeoutCopy the code

Blpop and BRPOP are blocking versions of LPOP and RPOP. They are basically the same except that they pop in different directions.

2.3.2 Application Scenarios

2.3.2.1 Message queue

The combination of Redis lpush+ BRPOP commands can block queues, the production client uses LRpush to insert elements from the left side of the list, and multiple consumer clients use BRPOP to block elements from the bottom of the list. Multiple clients ensure load balancing and high availability for consumption.

List can be combined flexibly and used in different scenarios, as summarized below:

  • Lpush + lpop = Stack (Stack)

  • Lpush +rpop=Queue

  • LPSH + LTRIM =Capped Collection

  • Lpush + brPOP =Message Queue

2.4, collections,

Collections are similar to hashsets in the Java language. There are no duplicate elements allowed in collections, and the elements in collections are unordered and cannot be retrieved by index subscripts.

Against 2.4.1, commands,

2.4.1.1. Operations within collections

  • Add elements
sadd key element [element ...]
Copy the code

Cannot add repeating element, adding repeating element returns 0.

  • Remove elements
srem key element [element ...]
Copy the code
  • Counting elements
scard key
Copy the code
  • Pops elements randomly from the collection
spop key
Copy the code

2.4.1.2 Inter-set operation

  • Find the intersection of multiple sets
sinter key [key ...]
Copy the code
  • Find the union of sets
suinon key [key ...]
Copy the code
  • Find the difference of multiple sets
sdiff key [key ...]
Copy the code

2.4.2 Application Scenarios

2.4.2.1, labels,

A typical usage scenario for collection types is tags. For example, one user may be interested in entertainment and sports, while another may be interested in history and news. These points of interest are tags. With this data, you can get people who like the same tags and users who like the same tags. This data is important for user experience and user engagement.

2.4.2.2 Common concern

The “common concern” function of social community users can be realized by using the operation of intersection.

2.5. Ordered collections

Zset is probably the most characteristic data structure provided by Redis. It is similar to the combination of Java SortedSet and HashMap. On the one hand, it is a set that ensures the uniqueness of internal values. On the other hand, it can assign a score to each value, representing the ranking weight of the value.

The ordered set provides the function of obtaining the specified score and element range query, calculating the ranking of members and so on. The rational use of the ordered set can help

We solve a lot of problems in actual development.

Elements in an ordered set cannot be repeated, but score can be repeated, just as student numbers in a class cannot be repeated, but test scores can be the same.

2.5.1 and orders

2.5.1.1 Within the set

  • Add members
zadd key score member [score member ...]
Copy the code

Add user and his score250 to the ordered set user: rank.

127.0.0.1:6379> zadd user:ranking 250 李四
(integer) 1
Copy the code
  • Counting members
zcard key
Copy the code
  • Calculates a member’s score
zscore key member
Copy the code
  • Calculates the ranking of members
zrank key member zrevrank key member
Copy the code
  • Delete members
zrem key member [member ...]
Copy the code

2.5.1.2 Inter-set operations

  • intersection
zinterstore destination numkeys key [key ...]  [weights weight [weight ...]] [aggregate sum|min|max]Copy the code
  • And set
zunionstore destination numkeys key [key ...]  [weights weight [weight ...]] [aggregate sum|min|max]Copy the code

2.5.2 Application Scenarios

Ordered collections are best used where ranking is required.

2.5.2.1 Statistics of user likes

It can be used to count the likes of works on blogs, video websites, etc., and rank works according to the likes.

3. Internal encoding of basic data types

So far, we have seen five basic data structures. If they are called data structures, they must have internal components. For example, in Java, strings are composed of char or byte arrays. Let’s take a quick look at the internal encoding of Redis’s five basic data structures.

3.1. Strings

There are three internal encodings for string types:

  • Int: a long integer of 8 bytes.

  • Embstr: contains a string of 39 bytes or less.

  • Raw: The string contains more than 39 bytes.

3.2, the hash

There are two internal encodings of hash types:

  • Ziplist (compressed list) : Redis uses ziplist as an internal hash implementation when the number of hash elements is less than the hash-max-ziplist-entries configuration (512 by default) and all values are less than the hash-max-ziplist-value configuration (64 bytes by default). Ziplist is better at saving memory than HashTable because it uses a more compact structure to store multiple elements consecutively.

  • Hashtable: When the hash type does not meet ziplist requirements, Redis uses Hashtable as an internal hash implementation because ziplist read/write efficiency is reduced and hashTable read/write time complexity is O (1).

3.3 list,

There are two internal encodings for list types.

  • Ziplist (compressed list) : When the number of list elements is smaller than the list-max-ziplist-entries configuration (512 by default) and the value of each element is smaller than the list-max-ziplist-value configuration (64 bytes by default), Redis uses Ziplist as an internal implementation of lists to reduce memory usage.

  • Linkedlist (linkedlist) : Redis uses linkedlist as an internal implementation of a list when the list type does not meet ziplist’s criteria.

3.4, collections,

There are two internal encodings for collection types:

  • Intset: Redis uses intset as its internal implementation for collections where all elements are integers and the number of elements is less than the set-max-intset-entries configuration (512 by default) to reduce memory usage.

  • Hashtable: Redis uses Hashtable as an internal implementation of the collection when the collection type does not satisfy intSet criteria.

3.5. Ordered sets

There are two internal encodings for ordered collection types:

  • Ziplist (compressed list) : Redis uses ziplist as an internal implementation of ordered collections when the number of elements is less than the zset-max-Ziplist-entries configuration (128 by default) and the value of each element is less than the zset-max-Ziplist-value configuration (64 bytes by default). Ziplist can effectively reduce memory usage.

  • Skiplist: Ordered collections use Skiplist as an internal implementation when ziplist conditions are not met, because ziplist reads and writes become less efficient.

This is just a brief overview. If I have the opportunity in the future, I will further study the implementation of Redis to have a deeper understanding of the internal principles of the basic data structure of Redsi.





Reference:

[1] : Redis Development and Operation

[2] : Gold Digging booklet Redis Deep Adventure: Core Principles and Application Practice