Redis data type and Application Scenario, redis data type scenario

Source: Internet
Author: User

Redis data type and Application Scenario, redis data type scenario

I. redis features
  • All data is stored in memory and read/write at high speed

  • Provides a wide range of data types: string, hash, set, sorted set, bitmap, hyperloglog

  • The AOF and RDB data persistence methods are provided to ensure that data is not lost after Redis is restarted.

  • All Redis operations are atomic. It also supports atomic operations after merging several operations and transactions.

We usually store data in relational databases, but to improve application performance, we should cache frequently accessed data that will not change frequently to the memory .. Redis does not have as powerful query functions as MySQL-type relational databases. You need to consider how to properly map data in relational databases to the cached key-value data structure.

Ii. Design Redis Key

Piecewise Design Method -- separate multiple meanings of keys using colons. The steps are as follows:

  1. Convert table name to key prefix

  2. Primary Key name (or other fields commonly used for search)

  3. Primary Key Value

  4. The field to store.

Eg. user table)

Id Name Email
1 Zj 156577812@qq.com
2 Ai 156577813@qq.com

This simple table may often have this requirement:> to query the user's email address based on the user id, you can choose to save the email address data to redis:

 
 
  1. set user:id:1:email 156577812@qq.com;

  2. set user:id:2:email 156577812@qq.com;

Iii. application scenarios of the String data type 1. Introduction

The string type is the most basic data type and the most common data type in Redis. It is even used by many players as the only data type in redis. The string type is binary safe in redis, which means that the string value cares about the binary string and does not care about the specific format, you can use it to store strings in json or JPEG format.

2. Data Model

The string type is the basic Key-Value structure. The Key is the unique identifier of a data in Redis, and the Value is the specific data.

Key Value
'Name' 'Redis'
'Type' 'String'
3. Application Scenario (1) store the value of a field in MySQL

Design the key as the table name: primary key value: field name

Eg.

 
 
  1. set user:id:1:email 156577812@qq.com

(2) storage objects

The string type supports strings of any format. strings that are stored in json or formatted by other objects are the most widely used strings. (Hash data type is recommended in this scenario)

 
 
  1. set user:id:1 [{"id":1,"name":"zj","email":"156577812@qq.com"},{"id":1,"name":"zj","email":"156577812@qq.com"}]

(3) generate auto-incremental id

When the value of the string type of redis is in the integer form, redis can perform the auto-increment (incr) Auto-subtraction (decr) operation as an integer. Because all redis operations are atomicDo not worry about transactions that may occur during multi-Client ConnectionProblem.

Iv. application scenarios of hash Data Types 1. Introduction

The hash type is similar to a relational database data table. The hash Key is a unique Value, and the Value part is a hashmap structure.

2. Data Model

Assume that a database table is as follows:

Id Name Type
1 Redis Hash

If you want to store data in the hash structure of redis, the data model is as follows:

The hash data type has the advantage of being more flexible and faster than the string type when storing the above data. Specifically, strings in json format must be converted and parsed when the string type is used for storage, even if no conversion is required, hash is dominant in terms of memory overhead.

3. Application scenarios

The hash type is very suitable for storing object-type data. Compared with converting objects to json string storage described in string, the hash structure can be used to add or delete 'field name' as needed, which is more efficient and flexible.

 
 
  1. hset user:1 name zj email 156577812@qq.com

V. application scenarios of the list Data Type 1. Introduction

A list is a string linked list sorted by insertion sequence. you can insert new elements in the header and tail (two-way linked list implementation. The time complexity of adding elements to both ends is O (1 )). When an element is inserted, if the key does not exist, redis will create a new linked list for the key. If all the elements in the linked list are removed, the key will also be removed from redis.

2. Data Model

In common operations, use the lpush command to insert elements in the list header and use the rpop command to retrieve data at the end of the list.

3. Application scenarios (1) Message Queue

The list Data Type of redis is the most economical and simple way for most users to implement queue services.

(2) "latest content"

Because the data performance near the two ends of the list structure is very good, it is suitable for some scenarios that need to obtain the latest data, such as the "Recent News" of news applications ".

4. Optimization suggestions

List is a linked list structure. If you insert data into the header and tail, the performance will be very high and will not be affected by the length of the linked list. However, if you insert data into the linked list, the performance will get worse and worse.

Vi. application scenarios of the set Data Type 1. Introduction
  • The set data type is a set (no sorting, no duplicates). You can add, delete, and determine whether the set data exists (the time complexity is O (1 ))

  • The set does not allow repeated data. If the added data already exists in the set, only one copy is retained.

  • The set type provides aggregation operations between multiple sets, such as intersection, union, and population. These operations are completed within redis and are highly efficient.

2. Data Model

3. Application scenarios

The set type features a set of data that is not repeated and unordered, and has rich computing functions. In some specific scenarios, it can efficiently solve the work that is not convenient for general relational databases.

1. "shared friend list"

In social applications, it is very complicated to use MySQL to obtain the common friends of two or more people, Weibo, which is shared by two or more people, you can save each person's friend id to the collection, and the operation of getting a common friend can be simply done with a command to take the intersection.

 
 
  1. // Replace the id with the name to facilitate reading.

  2. sadd user:wade james melo paul kobe

  3. sadd user:james wade melo paul kobe

  4. sadd user:paul wade james melo kobe

  5. sadd user:melo wade james paul kobe

  6. // Obtain the mutual friends of wade and james

  7. sinter user:wade user:james

  8. /* Output:

  9. *      1) "kobe"

  10. *      2) "paul"

  11. *      3) "melo"

  12. */

  13. // Get the friends of the four brothers of bananas

  14. sinter user:wade user:james user:paul user:melo

  15. /* Output:

  16. *      1) "kobe"

  17. */

  18. /*

  19. There are many other similar requirements. You must store the article IDS under each tag in the collection, and you can easily find several articles under Different tags;

  20. By saving everyone's interests in the collection, you can easily find the common interests of several people.

  21. */

VII. application scenarios of sorted set Data Type 1. Introduction

Each element in the set is associated with a score based on the set. data inserted into the sorted set is automatically sorted Based on the score.

2. Application scenarios

Adding sorting to a set type is an application scenario of an ordered set. For example, a friend list is displayed based on the "intimacy" sorting of friends.

 
 
  1. // Use the score of an element to indicate intimacy with friends.

  2. zadd user:kobe 80 james 90 wade  85 melo  90 paul

  3. // Sort friends by intimacy

  4. zrevrange user:kobe 0 -1

  5. /**

  6. * Output:

  7. *      1) "wade"

  8. *      2) "paul"

  9. *      3) "melo"

  10. *      4) "james"

  11. */

  12. // Increase the intimacy of friends

  13. zincrby user:kobe 15 james

  14. // Sort friends by "intimacy" again

  15. zrevrange user:kobe 0 -1

  16. /**

  17. * Output:

  18. *      1) "james"

  19. *      2) "wade"

  20. *      3) "paul"

  21. *      2) "melo"

  22. */

  23. // Similar requirements are also applied to sorting the document list based on the reading volume or likes of the article.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.