Redis is a NoSQL database based on key and value pairs. Its values are mainly composed of five basic data structures: string, hash, list, set, and Zset. In addition, some other data structures and algorithms are supported. Keys are composed of strings, so what are the use scenarios of these five data structures? Take a look!

A string

The string type is the basic data structure of Redis. The string type can be JSON, XML or even binary image data, but the maximum value cannot exceed 512MB.

1.1 Internal Coding

Redis will decide which internal encoding to use based on the type and length of the current value.

There are three internal encodings for string types:

  1. Int: a long integer of 8 bytes.
  2. Embstr: a string of no more than 39 bytes.
  3. Raw: a string of more than 39 bytes.

1.2 Application Scenarios

1.2.1 cache

In web services, MySQL is used as the database and Redis as the cache. Because Redis supports high concurrency, it typically speeds up reads and writes and reduces backend stress. Most requests on the Web end are to obtain data from Redis. If there is no data required in Redis, the data will be obtained from MySQL and written to Redis.

1.2.2 count

In Redis, there is a string related command incr key. The incr command increments the value and returns the following results:

  • The value is not an integer
  • The value is an integer and returns the increment
  • The key does not exist. The default key is0To return to1

For example, the number of articles read, the number of videos played and so on will use Redis to count, each play, the corresponding number of plays will be increased by 1, and these data will be asynchronously stored in the database for the purpose of persistence.

1.2.3 sharing Session

In A distributed system, each request of the user accesses A different server, which will lead to the problem of session asynchronization. For example, A request to obtain user information falls on server A, and the user information is stored in session after it is obtained. The next request falls on server B. If you want to obtain the user information from the session, it cannot be obtained normally, because the session of the user information is on server A. To solve this problem, use Redis to centrally manage these sessions and store the sessions in Redis. When using, just get it directly from Redis.

1. The speed limit

For security purposes, some websites restrict the number of visits to an IP address to n times within a certain period.

Two hash

In Redis, a hash type is a storage structure for a key-value pair.

2.1 Internal Coding

There are two kinds of internal codes for hash types:

  • Ziplist: When the number of hash type elements is less thanhash-max-ziplist-entriesSet (512 by default) and all values are less thanhash-max-ziplist-valueConfiguration (64 bytes by default). Ziplist uses a more compact structure to store multiple elements contiguously, thus saving more memory than Hashtable.
  • Hashtable: HashTable is used when the ziplist does not meet the requirements.

2.2 Application Scenarios

Because the hash type stores a key-value pair, for example, a database has the following user table structure

id name age
1 Java journey 18

Select id from redis where id is the key and user attribute is the value.

Hset user:1 name Java Journey age 18Copy the code

Using hash storage is more intuitive than using strings

List three

List types are used to store multiple ordered strings. A list can hold up to 2^32-1 elements. Elements can be inserted and ejected at either end of the list.

3.1 Internal Coding

There are two internal codes for lists:

  • Ziplist: When the number of hash type elements is less thanlist-max-ziplist-entriesSet (512 by default) and all values are less thanlist-max-ziplist-valueConfiguration (64 bytes by default). Ziplist uses a more compact structure to store multiple elements contiguously, thus saving more memory than Hashtable.
  • Linkedlist: A linkedList is used when the ziplist doesn’t fit the bill.

3.2 Application Scenarios

3.2.1 Message Queue

Lists are used to store multiple ordered strings, and since they are ordered, they satisfy the characteristics of message queues. Use lpush+ RPOP or Rpush + LPOP to implement message queues. In addition, Redis supports blocking operations, using the blocking command to block queues when elements are ejected.

3.2.2 stack

Because the list storage is an ordered string, meet the characteristics of the queue, also can meet the characteristics of the stack advanced after the use of Lpush + LPOP or Rpush + RPOP stack.

3.2.3 List of articles

This is because not only are the elements of a list ordered, but it also supports retrieving elements by index range. So we can use the lrange key 0 9 command to get the list of articles in pages

Four sets

A collection type can also hold multiple string elements; unlike a list, no duplicate elements are allowed and the elements in the collection are unordered. A collection can hold up to 2^32-1 elements.

4.1 Internal Coding

There are two kinds of internal encodings for collection types:

  • Intset: when the elements in the set are all integers and the number of elements is less thanset-max-intset-entriesRedis uses intSet as the internal implementation of the collection when configuring (512 by default) to reduce memory usage.
  • Hashtable: A Hashtable is used when the intset fails.

4.2 Application Scenarios

4.2.1 User Labels

For example, one user is interested in basketball and football, while another is interested in rugby and table tennis. These points of interest are a tag. With this data, you can get the people who like the same tags, and the tags that users are interested in. When you label a user, you need to (1) label the user and (2) add users to the label. You need to add transactions to the two operations.

  • Label the user
sadd user:1:tags tag1 tag2
Copy the code
  • Add a user to the label
sadd tag1:users user:1

sadd tag2:users user:1
Copy the code

Use the intersection (sinter) to find the common tag of the two users

sinter user:1:tags user:2:tags
Copy the code

4.2.2 Lucky draw function

There are two commands in the collection that support getting random numbers. They are:

  • Get a random count of elements, and the number of elements in the set is the same

srandmember key [count]

  • Randomly pop up count elements, elements pop up from the set, the number of elements in the set changes

spop key [count]

The user clicks the draw button, the parameter draw, puts the user number into the set, and then draws the first prize and second prize respectively. If the user who has won the first prize cannot draw the second prize by parameters, spop will be used; otherwise, SrandMember will be used.

Chapter V Ordered set

Ordered collections, like collections, cannot have duplicate elements. But you can sort, and it gives each element a score to sort by. You can store up to 2^32-1 elements.

5.1 Internal Coding

There are two internal encodings for ordered collection types:

  • Ziplist: when the number of elements in the ordered collection is smaller than in the list-max-ziplist-entries configuration (128 by default) and all values are smaller than in the list-max-ziplist-value configuration (64 bytes by default). Ziplist uses a more compact structure to store multiple elements contiguously, saving more memory.

  • Skiplist: Skiplist is used when ziplist requirements are not met.

5.2 Application Scenarios

5.2.1 list

When a user posts n articles, other people see the articles and give the likes of the articles, the score is used to record the number of likes, and the ordered collection ranks the articles according to the score. The process is as follows

A user posts an article with an initial “like” score of 0

zadd user:article 0 a
Copy the code

Someone likes article A, incrementing by 1

zincrby user:article 1 a
Copy the code

Query and like the first three posts

zrevrange user:article 0 2
Copy the code

Query the three articles after the “like”

zrange user:article 0 2
Copy the code

5.2.2 Delayed message queues

Order system, the order needs to be paid within 15 minutes, if not paid within 15 minutes, the order will be cancelled automatically. The time 15 minutes after the order is taken as the score, and the order is stored in Redis as the value. The consumer polls to consume. If the consumption is greater than or equal to the score of this record, this record will be removed from the queue and the order will be cancelled.

conclusion

In the development, the string type is the most used data type, which leads to the neglect of the other four data types of Redis. The selection of specific data types in specific scenarios is of great help to improve the performance of Redis. Redis supports message queues, but does not support ACK. As a result, redis’s implementation of message queues does not guarantee the reliability of messages unless it implements its own message acknowledgement mechanism, which is very cumbersome, so it is recommended to use a dedicated message queue for important messages.


Pay attention, don’t get lost

If you think the article is good, welcome to follow, like and collect, your support is the motivation of my creation, thank you all.

If there is a problem with the article, please do not be stingy, welcome to leave a message, I will check and modify in time.

If you want to know more about me, you can search “Java Journey” on wechat. Reply to “1024” and you can get learning videos and exquisite e-books. Every day at 7:30 on time push technical articles, so that your way to work is not lonely, and there are monthly book activity, help you improve hard strength!