Our task is introduced

This blog is a complete tutorial document for my Github project Our-Task: A complete list management system. If you are interested, you can check it out

string

Strings are the most basic data type in Redis, from which several other data structures are built.

The cache

The typical scenario is: Redis as a cache layer, Mysql as a storage layer, when the request comes, first according to the key name from Redis search, find the key directly take out the key value, if not found the key, query from Mysql, and the query result back to Redis, at the same time set the key expiration time. In this case, the vast majority of requests are read from Redis.

For example, if there is a record in the database user table whose ID is 1 and username is Xiao Feng, the key can be our-task:user:1:username and the corresponding value is Xiao Feng. In this case, the key is named as — Database name: table name: ID: attribute name

Of course, naming the key in this way will be longer and take up more memory, so we need to minimize the length of the key name as long as we can clearly describe the meaning of the key

The speed limit

Just like getting a captcha on a mobile phone, we find that every time we get a captcha, it takes another minute to get a captcha again, to protect our SMS interface from frequent access.

Specific measures are as follows:

isExists = redis.set(key, 1, "EX" 60, "NX") if(isExists ! = null | | redis. Incr (key) < = 5) by} {/ / / / "EX" 60 said set the key of the expiration time for 60 seconds / / "NX", said the key only when the key does not exist, // redis.incr(key) Increases the value of the key by 1 each timeCopy the code

In other words, this code says that the key is called no more than five times per minute

Sharing Session

Distributed services use share balancing to allocate users’ access to different servers. However, if users’ sessions are stored on their own servers, users will need to re-log in when refreshing. Therefore, Redis can be used to centrally manage sessions. Every time a user needs to get a Session, it gets it directly from Redis.

The hash

Redis itself is a database of key-value pairs, a key corresponds to a value, hash type means: the value itself is a hash structure.

Storing database tables

In a relational database, our tables are stored like this

id name age sex
1 Xiao Ming 15 female
2 Small wind 22 male

Using the Redis hash to store, our table can be accessed in this way

The key is: user:1 and the corresponding values are shown in the table below

id 1
name Xiao Ming
age 15
city female

To obtain the name of user 1, run the following command: hget user:1 name

Change the name corresponding to ID 1 to: Xiao Zhang, then you can write:

Hset user:1 name Xiao ZhangCopy the code

The list of

Redis lists are used to store multiple ordered strings, ordered in the sense that the elements are placed in sequence, such as from the right, and the elements go to the last position in the list. Each string is also called an element, and the elements in the list can be repeated. You can insert and pop these elements, and get a list of elements in a specified range. You can also get values by subscript, such as 0, the first element, -1, the last element, and so on

The message queue

Because the list can be inserted and ejected at both ends, it can be used as a message queue. Producers insert production elements at one end, and consumers consume data at the other.

The stack

Using Lpush and LPOP, insert at one end and pop at the same time, you can implement the stack structure

The queue

Similar to message queues, you can insert at one end and pop at the other

A collection of

Collections are also used to hold multiple elements, but unlike lists, collections do not allow duplicate elements. In addition, the elements in collections are unordered, so they cannot be indexed by subscripts. Redis not only supports the addition, deletion, change and search of elements in the set, but also supports the operation of union and intersection between sets.

The label

Tags are typical usage scenarios for collections. Take our Task for example. A list is called “Write code” and I can put it under “work” or I can put it under “learn”

Task :1:label = task:1:label = task:1 Using the collection operation provided by Redis, it is very convenient for us to add, delete, change and check.

Lucky draw

For the lottery process, we all know that when a number x is extracted, x can no longer be drawn, that is, removed. If we use the set to achieve, we can put some numbers into the set. Then use the following method to implement the lottery.

Spop: Removes and returns an element from the collection

Srandmember: Returns one or more random numbers in the collection (without removing elements)

An ordered set

Ordered collections are also collections that can be sorted, but unlike lists that are sorted by subscripts, ordered collections are sorted by a score, similar to the following table

score Member (Student Number)
1 34343
50 34323
100 54443

Although the elements can not be repeated, but the score can be repeated, just like the test score in the class, the score can be repeated, but the student number of each person can not be repeated

Leaderboard system

Let’s say a user uploads a video that has a few likes

For every “like”, we can add 3 points to that user’s video

If the user cheats, we can just delete the user, or delete the video of the user, from the ordered collection

We can also get the top 10 videos by using the ordered set method: ZRevRange (returns the members of the ordered set within the specified range, with the score from highest to lowest by index)

These operations, and so on, can be implemented through the methods provided by ordered collections

String and hash summary

Lists and hashes, it seems, can store records in database tables, but we need to understand these features before we can use them flexibly in development

  • String type: Each attribute is a key
    • Advantages: Simple and intuitive, each attribute can be updated and deleted
    • Disadvantages: Too many keys, large memory, no correlation between attributes, generally not considered in production environment
  • Hash type: Each attribute is a pair of field-values, but is held by a key
    • Advantages: simple and intuitive, reasonable use can reduce memory space
    • Disadvantages: Pay attention to the length of the storage, otherwise the hash will be converted between ziplist and Hashtable internal encodings, hashtable consumes more memory