For in-depth study of “Redis”, there is a complete set of Redis interview questions (attached analysis), guide learning knowledge route outline (hand-painted XMIND version), handwritten notes PDF, etc., if you need to study together → stamp here

First, “Five basic” data types

Redis expects all keys to be strings. When we talk about basic data structures, we are talking about the data types that store values, including five common data types: String, List, Set, Zset, and Hash

1.1 Introduction to Redis data structure

Redis has many basic data structure types, and I recommend reading the official Redis website for basic data structure types, and then reading the summary below

First, for Redis, all keys are strings. When we talk about basic data structures, we are talking about the data types that store values, including five common data types: String, List, Set, Zset, and Hash.

1.2 Basic data structure details

The content is actually quite simple, I think the key to understand is how to use this structure, what can be used to do? So I elaborated around legend, command, execution and scene

1.2.1 String The character String is a String

String is the most basic data type in Redis. Each key corresponds to a value.

The String type is binary safe, meaning that a Redis String can contain any data. Such as numbers, strings, JPG images or serialized objects.

  • legend

Here is an example of String with the key hello and the value world

  • Command to use

  • Command execution

    127.0.0.1:6379> set hello world OK 127.0.0.1:6379> get hello “world” 127.0.0.1:6379> del hello (integer) 1 127.0.0.1:6379> get hello (nil) 127.0.0.1:6379> get counter “2” 127.0.0.1:6379> incr counter (integer) 3 127.0.0.1:6379> get counter “3” 127.0.0.1:6379> incrby counter 100 (integer) 103 127.0.0.1:6379> get counter “103” 127.0.0.1:6379> decr counter (integer) 102 127.0.0.1:6379> get counter “102”

  • Actual combat scene

  1. Cache: The classic usage scenario, the common information, strings, pictures or videos and other information into Redis, Redis as the cache layer, mysql as the persistence layer, reduce mysql read and write pressure.
  2. Counters: Redis is a single-threaded model, one command is executed before the next, and data can be dropped to other data sources.
  3. Session: Common solution Spring Session + Redis realizes session sharing

1.2.2 List List

The List in Redis is actually a linked List.

Using the List structure, we can easily implement the latest message queuing function (such as sina Weibo TimeLine). Another use of lists is message queues, where tasks can be stored in a List using a PUSH operation and then pulled out by a worker thread for execution using a POP operation.

  • legend

  • Command to use

  • The technique of using lists
  1. Lpush + lpop = Stack (Stack)
  2. Lpush +rpop=Queue
  3. Lpush + LTRIM =Capped Collection
  4. Lpush + brPOP =Message Queue
  • Command execution

    127.0.0.1:6379> lpush myList 12 ll ls mem (integer) 5 127.0.0.1:6379> lrange myList 0-1

    1. “mem”
    2. “ls”
    3. “ll”
    4. “2”
    5. “1”

    127.0.0.1:6379> lindex mylist -1 “1” 127.0.0.1:6379> lindex mylist 10 # index not in range of mylist (nil)

  • Actual combat scene micro-blog

  1. TimeLine: Someone posts a tweet and adds lpush to the TimeLine to show new list information.
  2. The message queue

1.2.3 Set collection

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).

  • legend

  • Command to use

  • Command execution

    127.0.0.1:6379> sadd myset hao hao1 xiaohao hao (integer) 3 127.0.0.1:6379> smember myset

    1. “xiaohao”
    2. “hao1”
    3. “hao”

    127.0.0.1:6379> sismember myset hao (integer) 1

  • Actual combat scene

  1. Tag, you can tag the user, or the user can tag the message, so that the same tag or similar tag can be used to recommend things or people to follow.
  2. Click like, or click on, favorites, etc., can be put into the set to achieve

1. The Hash Hash

Redis hash is a mapping of string fields and values, and hash is especially useful for storing objects.

  • legend

  • Command to use

  • Command execution

    127.0.0.1:6379> hset user Name1 hao (INTEGER) 1 127.0.0.1:6379> hset user email1 [email protected] (integer) 1 127.0.0.1:6379> hgetall user

    1. “name1”
    2. “hao”
    3. “email1”
    4. [email protected]

    127.0.0.1:6379> hget user user (nil) 127.0.0.1:6379> hget user name1 “hao” 127.0.0.1:6379> hset user name2 xiaohao (integer) 1 127.0.0.1:6379> hset user email2 [email protected] (integer) 1 127.0.0.1:6379> hgetall user

    1. “name1”
    2. “hao”
    3. “email1”
    4. [email protected]
    5. “name2”
    6. “xiaohao”
    7. “email2”
    8. [email protected]
  • Actual combat scene

  1. Cache: intuitive, more space saving than String, the maintenance of cache information, such as user information, video information, etc

1.2.5 Zset ordered set

Redis ordered collections, like collections, are collections of string elements and do not allow duplicate members. The difference is that each element is associated with a double score. Redis uses scores to sort the members of a collection from smallest to largest.

The members of an ordered set are unique, but the score can be repeated. Collections are implemented by hashing tables, so adding, deleting, and searching are O(1) complexity.

  • legend

  • Command to use

    127.0.0.1:6379> zadd myscoreset 100 hao 90 xiaohao (integer) 2 127.0.0.1:6379> ZRANGE myscoreset 0-1

    1. “xiaohao”
    2. “hao”

    127.0.0.1:6379> myscoreset hao “100”

  • Actual combat scene

  1. Leaderboards: An ordered collection of classic usage scenarios. For example, websites such as novel videos need to make a ranking of novel videos uploaded by users. The ranking can be scored according to the number of users’ attention, update time, word count and so on

Two, three special types of detailed explanation

In addition to the five basic data types mentioned above, Redis also has three special data types, namely HyperLogLogs (cardinal statistics), Bitmaps (Bitmaps) and Geospatial (geographic location).

2.1 HyperLogLogs (Cardinal Statistics)

Redis version 2.8.9 updates the Hyperloglog data structure!

  • What is the cardinal number?

For example, A = {1, 2, 3, 4, 5}, B = {3, 5, 6, 7, 9}; So cardinality (non-repeating elements) = 1, 2, 4, 6, 7, 9; (Error tolerance, that is, acceptance of certain errors)

  • What problems are HyperLogLogs radix statistics used to solve?

This structure can be very saving to count various counts, such as registered IP number, daily access to the number of IP page real-time UV, online users, number of mutual friends, etc..

  • What are its advantages?

For a large website with, say, 1 million IP addresses per day, one IP consumes 15 bytes, so 1 million IP addresses is 15 megabytes. However, HyperLogLog occupies 12K for each key in Redis, and its theoretical storage is approximately 2^64 values. No matter what the stored content is, its algorithm based on cardinality estimation can only accurately estimate the cardinality, and it can use a small amount of fixed memory to store and identify the unique element in the set. And the base of this estimate is not necessarily accurate, it is an approximation with 0.81% standard error (which is negligible for business scenarios that accept some tolerance, such as IP number statistics, UV, etc.).

  • Usage of related commands

    127.0.0.1:6379> pfadd key1 a b c d e f g h I # Create the first group of elements (integer) 1 127.0.0.1:6379> pfcount key1 # Number of cardinality of statistics elements (integer) 9 127.0.0.1:6379> pfadd key2 c j k l m eg a # create a second group of elements (integer) 1 127.0.0.1:6379> pfcount key2 (integer) 8 127.0.0.1:6379> pfmerge key3 key1 key2 # Merge two groups: key1 key2 -> key3 merge OK 127.0.0.1:6379> pfcount key3 (integer) 13

2.2 Bitmap (Bit Storage)

Bitmaps, or Bitmap data structures, manipulate binary bits for recording, with only 0 and 1 states.

  • To solve what problem?

For example: statistics user information, active, inactive! Logged in, not logged in! Punch, don’t punch! You can use Bitmaps for both!

How much memory does it take to store a year’s worth of clocking? 365 days = 365 bits 1 byte = 8bits 46 bytes!

  • Usage of related commands

Use bitmap to record your clocking from Monday to Sunday! Monday: 1 Tuesday: 0 Wednesday: 0 Thursday: 1……

127.0.0.1:6379> setbit sign 0 1
(integer) 0
127.0.0.1:6379> setbit sign 1 1
(integer) 0
127.0.0.1:6379> setbit sign 2 0
(integer) 0
127.0.0.1:6379> setbit sign 3 1
(integer) 0
127.0.0.1:6379> setbit sign 4 0
(integer) 0
127.0.0.1:6379> setbit sign 5 0
(integer) 0
127.0.0.1:6379> setbit sign 6 1
(integer) 0
Copy the code

Check to see if you clocked in on a particular day!

127.0.0.1:6379> getbit sign 3
(integer) 1
127.0.0.1:6379> getbit sign 5
(integer) 0 
Copy the code

Statistical operation, statistics of the number of days!

127.0.0.1:6379> bitcount sign # (integer) 3Copy the code

2.3 Geospatial

Redis Geo is available in Redis 3.2! The function extrapolates geographic information: the distance between two places, and the number of people in a radius of several miles

2.3.1 geoadd

Add geographic location

Taiyuan 123.43 41.80 shenyang (INTEGER) 3 127.0.0.1:6379> Geoadd China: City 144.05 22.52 shengzhen 120.16 30.24 Hangzhou 108.96 34.26 Xian (integer) 3Copy the code
  • The rules

The two levels cannot be added directly, we usually download the city data (the website can be found at GEO: www.jsons.cn/lngcode)!

  • Effective longitude ranges from -180 degrees to 180 degrees.

  • Valid latitudes range from -85.05112878 degrees to 85.05112878 degrees.

    This command returns an error when the coordinates are outside the range specified above.

    127.0.0.1:6379> geoadd China: City 39.90 116.40 Beijin (error) ERR invalid longitude, Latitude pair 39.900000,116.400000

2.3.2 geopos

Gets the longitude and latitude of the specified member

Geopos China: City Taiyuan manjing 1) 1) "112.54999905824661255" 1)" "118.75999957323074341" 1) "32.03999960287850968"Copy the code

Get the current position, must be a coordinate value!

2.3.3 geodist

If it does not exist, return null

  • The unit is as follows
  1. m

  2. km

  3. Mi miles

  4. Ft feet

    Taiyuan Shenyang M “1026439.1070” 127.0.0.1:6379> Geodist China: City taiyuan shenyang M “1026439.1070 Km “1026.4391”

2.3.4 georadius

Nearby people ==> Get the addresses of all nearby people, location, and query by radius

A person who gets a specified amount

127.0.0.1:6379> Georadius China: City 110 30 1000 km Taiyuan: City 110 30 500 km 1) "Xian" 2) "Hangzhou" 3) "Manjing" 4) "Georadius China: City 110 30 500 km 1)" Xian "2)" Hangzhou "3)" Manjing "4)" Georadius China: City 110 30 500 km 1) "Xian" 2) "Hangzhou" 3) "Manjing" 4) "Georadius China: City 110 30 500 km 1) "Xian" 127.0.0.1:6379> Georadius China: City 110 30 500 km withDist 1) 1) "xian" 2) "483.8340" 127.0.0.1:6379> Georadius China: City 110 30 1000 km WithCoord WithDist Count 2 1) 1) "xian" 2) "xian" 3) 1) "xian" 2) "34.25999964418929977" 2) 1) "manjing" 2) "864.9816" 3) 1) "118.75999957323074341" 2) "32.03999960287850968"Copy the code

Parameter Key Latitude and longitude radius unit [latitude and longitude to display results] [distance to display results] [Number of displayed results]

2.3.5 georadiusbymember

Displays other members within a radius of the specified member

Taiyuan 1000 km 1) "manjing" 2) "taiyuan" 3) "xian" 127.0.0.1:6379> Georadiusbymember China: City taiyuan 1000 km WithCoord WithDist Count 2) 1) 2) 3) "112.54999905824661255" 2) "37.86000073876942196" 2) 1) "2)" 2) "2)" "34.25999964418929977"Copy the code

The parameters are the same as georadius

2.3.6 GeoHash (rarely used)

This command returns an 11-character hash string

Geohash China: City Shenyang 1) "wxrvb9qyxk0"Copy the code

Convert a two-dimensional latitude and longitude into a one-dimensional string. The closer the two strings are, the closer they are

2.3.7 underlying

The underlying implementation principle of Geo is actually Zset. We can operate Geo through Zset command

127.0.0.1:6379 > type China: city zsetCopy the code

View all elements and delete the specified element

127.0.0.1:6379> zrange China: 0 -1 withscores 1) "xian" 2) "4040115445396757" 3) "hangzhou" 4) "4054133997236782" 5)  "manjing" 6) "4066006694128997" 7) "taiyuan" 8) "4068216047500484" 9) "shenyang" 1) "4072519231994779" 2) "shengzhen" 3) "4154606886655324" 127.0.0.1:6379> zrem China :city manjing (integer) 1 127.0.0.1:6379> zrange China :city 0-1 1) "xian" 2) "hangzhou" 3) "taiyuan" 4) "shenyang" 5) "shengzhen"Copy the code