Deep understanding of redis -- Introduction and application of five classic data types

Posted by MattSharp on Sat, 22 Jan 2022 02:48:43 +0100

1.String type and its application

2.hash type and its application

3.list type and its application

4.set type and its application

5.Zset type and its application

6. Summary

1.String type and its application
String type is our most commonly used type, and some people even use only this type.

//The most commonly used api
//Single value operation
set key value
get key
//Set / get multiple key values at the same time
MSET key value [key value ....]
MGET key [key ....]
//Increase or decrease in value
//Incremental number
INCR key
//Increase the specified number
INCRBY key increment
//Decreasing number
DECR key
//Decrements the specified integer
DECRBY key decrement
//Get string length
STRLEN key
//Distributed lock
set key value [EX seconds] [PX milliseconds] [NX|XX]

Usage scenario:
1) This type can be used to save general json objects (such as User information found in the table).
2) For example, to save the number of views and likes, you can use the self increasing function (regardless of thread safety).
3) Distributed lock is a time limited key and value value, which can ensure the serialization of program execution. It is a cross JVM lock, which will be systematically introduced in subsequent articles.
4) token and other information.

2.hash type and its application
The hash type is transformed into our JAVA data structure, which can be described by map < string, map < object, Object > >. Is a key whose value is composed of multiple keys and values

//The most commonly used api

//Set field values one at a time
HSET key field value
//Get one field value at a time
HGET key field
//Set multiple field values at once
HMSET key field value [field value ...]
//Get multiple field values at a time
HMGET key field [field ....]
//Get all values of the field
hgetall key
//Get all the quantities in a key
hlen
//delete
hdel

Suppose we want to save a user information now. Initially, we can save it in json:

However, after doing so, we found that we may only need to use the data of one or two fields of the user, but in this way, we have to sequence / deserialize all the user's information every time, which increases the overhead of the server. Is there a way we can accurately extract a certain attribute we need? At this time, you can use hash:


In this way, we can accurately obtain the field value of user information.

3.list type and its application
List must be commonly used in java, but in redis, list is a double ended linked list structure. The capacity is the 32nd power of 2 minus one element, about more than 4 billion. Its main functions include push/pop, etc.
Common APIs:

//Add an element to the left of the list
LPUSH key value [value ...]
//Add an element to the right of the list
RPUSH key value [value ....]
//view list
LRANGE key start stop
//Gets the number of elements in the list
LLEN key

Application scenario:
1) the official account of WeChat public.

As long as the author I follow publishes a new article, it will be broadcast to my list. When viewing the article, 10 articles will be displayed at a time, similar to paging:
lrange likearticle:UserId 0 9

However, the data generally does not save too ancient data. It may save about 2000 pieces. For more distant data, you have to query in the database.

2) Product review list
Comments on some products can be placed in a list, and then the time is sorted in descending order.

lpush items:comment:1001 {"id":1001,"name":"huawei","date":1600484283054,"content":"lasjfdljsa;fdlkajsd;lfjsa;ljf;lasjf;lasjfdlsad"}

3) Save paging information
Because the lrange command is like limit, you can use this command to support paging query. First prepare the data and put it into the cache before paging.

4) Drop down list of various transactions (recent data)
This principle is the same as the first one. The key point is that generally, redis only saves thousands of pieces of information, such as information in the past year. If you go forward, you have to check in the database.

4.set type and its application
The set type is implemented by hash table, which is characterized by no repetition of elements, and the intersection and difference sets of two sets can be taken at the same time.

//Common api

//Add element
SADD key member [member ...]
//Delete element
SREM key member [member ...]
//Traverses all elements in the collection
SMEMBERS key
//Determine whether the element is in the collection
SISMEMBER key member
//Gets the total number of elements in the collection
SCARD key
//Pop up an element randomly from the collection, and the element will not be deleted
SRANDMEMBER key [number]
//Pop up an element randomly from the collection, delete one by one
SPOP key [number]

//Set operation
//The difference set operation A-B of a set is a set composed of elements belonging to a but not to B
SDIFF key [key ...]

//The intersection operation A ∩ B of A set is A set composed of jointly owned elements belonging to A and B
SINTER key [key ...]
//The union operation A ∪ B of A set or the combined set of elements belonging to A or B
SUNION key [key ...]

Usage scenario:
1) Lottery scene
The command to pop up elements randomly from the collection can be used for lucky draw or Order By RAND() in the database.

2) Wechat friends circle praise
As we all know, wechat friends circle likes and only common friends will appear, so you can use the intersection method to obtain friends with common likes at this time.

3) People QQ may know
You can use the difference set operation of the set to recommend.

5.Zset type and its application
This is a set with scores. If we compare zset with set, we will find:
The difference between Zset and Set is that each element has a score attribute, and the elements are sorted from low to high according to the score during storage. This score can be time equivalent.
//Common APIs

//Add element
ZADD key score member [score member ...]
//According to the order of element scores from small to large
//Returns all elements of the index from start to stop
ZRANGE key start stop [WITHSCORES]
//Gets the score of the element
ZSCORE key member
//Delete element
ZREM key member [member ...]
//Gets the element of the specified score range
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
//Increase the score of an element
ZINCRBY key increment member
// Gets the number of elements in the collection
ZCARD key
//Gets the number of elements within the specified score range
ZCOUNT key min max
//Delete elements by ranking range
ZREMRANGEBYRANK key start stop
//Get the ranking of elements from small to large
ZRANK key member
//Get the ranking of elements from large to small
ZREVRANK key member

Usage scenario:
1) Product review list.
We used the list as the product comment list earlier. In fact, there will be bug s when the amount of data is large. If the data increases fast enough:
When you turn the first page, the data is the first page (normal)
When you turn to the second page, the content of the first page has been pushed to the second page, and the data is still the first page (exception)
However, when we use zset, because zset has a score field, we set this field as the creation time of the data. We can search according to the last time of the list found last time, so that the problem of previous data duplication will not occur.
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
2) Sort and display commodities according to commodity sales
Because of its own sorting function, this type is very easy to use for ranking display.

6. Summary

typeintroduceUsage scenario
StringFoundation and common typesCan store any data
HashKey value pair setYou can operate on a property of an object
ListBidirectional linked listPaging data can be stored
SetCollection of non repeating elementsIt can store non repeating elements and take intersection and difference sets
Sorted SetA collection of non repeating sortable elementsNon repeating elements can be stored and aligned for orderly sorting

Topics: Redis