Essential knowledge and application scenarios of redis data types

Redis is based on key-value pairs, and its key type is actually object, so the so-called redis data type is actually the value data type. From the big point of view, there are mainly the following five types:

  1. string
  2. list
  3. hash
  4. set
  5. sorted_set

string

The string type should be the most commonly used in redis. It can store strings, numeric values, and binary bitmap bitmaps.
So what does the string type actually store? It is actually a byte array . Redis has many commands for string type operations. Use the string length query command to verify whether it is a character or a byte.
The verification process is to store Chinese characters under different character set encodings, and you will find that the STRLENresult of use is not the number of characters, but the byte length of the corresponding character under the corresponding character set encoding.

The string type can store strings , so it also provides many basic and commonly used string manipulation functions, such as string splicing append, length query strlen, and obtaining characters at specific positions getrange.
In many designs involving permission systems, the string type is often used to store tokens and a certain validity period is set.

The above operations and the following operations can helpbe queried in redis-cli , for example, to query the functions supported by string, you can use it help @string.

The string type can store values , so it also provides a lot of operation functions for values, such as adding one incr, subtracting one decr, adding a specific value incrby, subtracting a specific value, decrbyetc.
This function will have a good application in business scenarios such as the amount of visits, comments, online and offline of certain functions of certain systems.

The string type can store bitmaps, and also provides many operations on bitmaps, such as setting bitmaps setbit, obtaining bitmap data getbit, bitmap statistics bitcount, and composite statistics bitop.
Bitmap is an operation based on binary bits. It can use a small memory to represent a large amount of data. It is very useful for many statistical businesses, such as data statistics for specific scenarios such as weeks, months, and days.
It should be noted that the offset in the bitmap is limited and cannot exceed the maximum limit of Integer, otherwise an exception will be thrown and the storage will fail.

When setting the value of the string type, you can use a single operation setor a multi-element operation mset. Whether it is a single-element operation or a multi-element operation, there is an operation with a trailing end nx. This operation supports nxand xxoperations, one is The value can be set successfully only when the key does not exist. One is that the value can be set successfully only when the key exists.
This function can ensure the atomicity of data to a certain extent, so it is often used for distributed locks in distributed application scenarios. (To be precise, atomicity is guaranteed for multi-element operations. Since redis is single-process and single-threaded, there is no atomicity problem for single-element operations)

list

The list type is also a very commonly used type in redis. The list type key has head and tail attributes, which point to the first element and the last element in the list respectively. This design allows the list type to simulate a variety of commonly used data structures.

To store elements in the list, you can choose to add data from the left or from the right, you can also choose linsertthis operation to insert data at a specific location, and you can also use lsetthis operation to replace the data at a specific location.
The above method of additional push has a corresponding pop-up data operation, you can choose to take out in the same direction, or you can choose to take out in reverse.
For the same-direction fetching operation, that is, lpushsum lpop, and rpushsum rpop, the result of this operation is data last in first out, just like the design of the data structure of the stack in java .
Reverse extraction, that is, lpushcorresponding rpop, or rpushcorresponding lpop, the result of this operation is first-in-first-out, the so-called FIFO, just the same data structure as the queue in java .
And linsert, lsetthis operation is the same as the array structure operation in java .
At the same time, list also supports asynchronous blocking. For example blpop, brpopthis operation will block the client until the corresponding key array is fetched. This operation can achieve some unicast subscription business requirements.
In the list type, the elements are allowed to be repeated, and from the order in which they can be taken, it can be seen that they are ordered, and this order is the order in which the data is stored.
In summary, the redis list type can replace some commonly used APIs and data structures in Java, and can better ensure the reliability of data to a certain extent.

The list type has many operations, which are not limited to those listed above. Like the string type, you can also use the help @listmethod to query the help documentation that comes with redis, and learn the actual corresponding when you need it.

hash

Redis itself is a key-value structure. The hash here means that value itself is a key-value pair. This structure is like a hashmap nested in a hashmap in java.
Therefore, the hash type of value itself is just like the string type of redis, but in fact most of the operations of hash are very similar to those of the String type.
From the operation command, it is almost a hcharacter added before the corresponding command of string. The operation of storing data is to add an inner key on the basis of the original key, but the standard name here is field.
Get fetches data, set saves data, and the addition and subtraction operations for values ​​are very similar to strings.

This structure of hash is very suitable for one object, multiple attributes, this kind of data storage. For example, the storage of some attributes of popular products and the storage of the condition data of a certain vehicle in the Internet of Vehicles can reduce the operation of the database when the popular data is used, and at the same time can modify the data conveniently and efficiently.

set

In terms of simply accessing data, the list type and set type in redis are actually very similar to the list and set in java. In java, both lists and sets are collections and containers, which can store many other types. Things are inside. The difference is that lists allow repetition and are ordered, while sets do not allow repetition.
As for the issue of set order, there are many set subclasses in Java, some are disordered, and some are ordered, so they cannot be generalized.
In redis, similar to java, set is not allowed to be repeated, but the set here is disordered.
The set does not allow repetitive features and has many application scenarios. For example, it can be used to count online users within a certain period of time, and users who are online multiple times can be directly removed.

In addition to the characteristics of the set data type itself, redis also provides some useful api commands for this type. For example, sinteryou can take the intersection of two set data, sdiffthe difference of suniontwo sets, and the union of two sets. set.
It should be noted here that sdiffthere is actually a direction, which will be based on the content of the leftmost key, so the actual direction needs to be controlled by yourself when you need to use it.
In addition, the above three operations all have an associated storeoperation. This operation needs to provide an additional key, and the results of intersection, union, and difference will be stored in this additional key.

The set type also has a very good operation, which can generate a certain random number according to a given key. The command is srandmemberthat this operation requires a key parameter and a number, which is the number of random numbers generated.
This number is very particular. If it is a positive number and is less than the number of elements in the set itself, it will randomly return a given number of unique data. If it is a positive number and is greater than the number of elements in the set itself, the data of the given data will be returned, but there will be duplication. If it is a negative number and is less than the number of elements in the set itself, the result may or may not be repeated. If it is negative and greater than the number of elements in the set itself, the given amount of data will also be returned, and there will be duplication.
Above this function, it is suitable for similar code, like the lottery business scenarios.

For set, there is an operation that needs attention, that is smembers, this operation can list all elements under a certain key, but this is an operation that consumes redis throughput and needs to be used with caution.

sorted_set

Sorted_set is an ordered set of sets. In a sense, sorted_set is more like a supplement to list and set. List is ordered (storage order), but does not de-duplicate, while set is de-duplicated, but disorderly.
Each of these designs naturally has its own advantages and each has its own application scenarios, but the need for repetition and order is also very common, and sorted_set is such a type, but the order here is different from the list. Not the order of deposit, but the sort.

The above statement is actually an understanding. It can be said that sorted_set is a supplement to list and set, or it can be said to be a synthesis. Because sorted_set's operation is more like a combination of list and set operations, it has intersection, union, and difference operations like set, and it also has operations that block data fetching like list.
But the difference is that the set operation in sorted_set also has weight and aggregation operations, which can take the maximum, minimum, and sum, which also makes it have more application scenarios.

sorted_set is an ordered type with sorting. Sorting here needs to be given a score when storing data. This point value can determine the order of the corresponding elements, but this point value does not mean that it will not change if it is given, it can be added and subtracted, and after the point value is operated, the corresponding order will also change at the same time.
This feature is very suitable for some real-time ranking data operations, such as song rankings, blog rankings, sales rankings, and so on.

Generally speaking, if there is sorting, there will be other additional data maintenance, which will inevitably lead to low efficiency under the same circumstances.
The special thing about sorted_set is that the underlying storage structure is skip list skip table, this structure stores more content than the key of the set, which improves the efficiency of sorted_sort (specific structure details to be added)

related articles

Caching and redis related basic knowledge
Linux redis installation and software installation related Linux knowledge points
redis data type key knowledge and application scenarios
redis pipeline, transaction, publish and subscribe, expiration, filter and other common advanced functions (part 1)
redis pipeline, A small note of commonly used advanced functions such as transactions, publish and subscribe, expiration, filters, etc. (Part 2)
Springboot integration and use of redis common functions

Guess you like

Origin blog.csdn.net/tuzongxun/article/details/107371302