Resources: Redis Final chapter

Redis has five basic data types: String, List, Hash, Set, and Sorted Set. Next, we will introduce each type and its application scenarios one by one.

String

String is the simplest and most commonly used data type. Data can be set or obtained using the set and GET methods in the following scenarios

  • ** Cache function: ** the most commonly used function, no one. For example, to a user objectJSONString, read and then converted back to the target object;
  • ** counter: ** is used to limit the number of requests to an interface, or count the number of clicks a user has, etcincrThe command is added automatically.Implementation counter

Hash

This is a map-like structure that sets or retrieves data through the hset and hGET methods. This structure has not been applied to the project for the time being.

List

A List is a simple List of strings, sorted in insertion order, with the head on the left and the tail on the right. You can add or remove elements from both ends. Common commands

Application Scenarios:

  • Message queues: You can use left-in and right-out, or right-in and left-out, with producers pushing data in at one end and consumers popping data out at the other. Redis implements message queues

    Note: This type of message queue requires consumers to poll continuously, and you can use either BLPOP or BRPOP, which block until there are no elements in the list.

Set

A Set is an unordered Set and is automatically de-duplicated. Common commands

The main feature of this data type is de-duplication. In distributed environment, you can use Redis set to achieve global data de-duplication.

Sorted Set

Sorted set can be both de-duplicated and Sorted. In contrast to set, when writing value, you also need to set score, and Redis automatically sorts the score from lowest to highest. Common commands

Application Scenarios:

  • ** Delay queue: ** With the task execution timestamp as score, the application constantly polls Redis for the element with the smallest score and compares score with the current timestamp.

  • ** Charts: ** Such as song charts, game charts. Multidimensional sort

    In most scenarios, we need to sort by multiple dimensions. For example, the list of software downloads is sorted by the number of downloads first, and then by the latest download date if the number of downloads is the same.

    For this two-dimension sort, since score is a floating point type, we can construct a special score with the integer part as downloads and the decimal part as download time, thus achieving a two-dimension sort.

    But what about three dimensions, four dimensions?

    Custom weight formula, such as Score = downloads *10000 + download time